SQLite table not created - ios

I have in my viewDidLoad() the below codes:
// Create a string containing the full path to the sqlite.db inside the documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"sqlite.db"];
// Check to see if the database file already exists
bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:databasePath];
// Open the database and store the handle as a data member
if (sqlite3_open([databasePath UTF8String], &databaseHandle) == SQLITE_OK)
{
// Create the database if it doesn't yet exists in the file system
if (!databaseAlreadyExists)
{
// Create the PERSON table
const char *sqlStatement = "CREATE TABLE IF NOT EXISTS PERSON (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRSTNAME TEXT, LASTNAME TEXT, BIRTHDAY DATE)";
char *error;
if (sqlite3_exec(databaseHandle, sqlStatement, NULL, NULL, &error) == SQLITE_OK)
{
// Create the ADDRESS table with foreign key to the PERSON table
sqlStatement = "CREATE TABLE IF NOT EXISTS ADDRESS (ID INTEGER PRIMARY KEY AUTOINCREMENT, STREETNAME TEXT, STREETNUMBER INT, PERSONID INT, FOREIGN KEY(PERSONID) REFERENCES PERSON(ID))";
if (sqlite3_exec(databaseHandle, sqlStatement, NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"Database and tables created.");
}
else
{
NSLog(#"Error: %s", error);
}
}
else
{
NSLog(#"Error: %s", error);
}
}
}
sqlite3_close(databaseHandle);
And I am expecting that both tables are created in the folder /Users/*/Library/Application Support/iPhone Simulator/5.1/Applications/*/Documents/.
But when I went to that folder and type sqlite3 and .schema, nothing shows up.
I did see that sqlite.db is created in that folder though.
Do you know why?

after copying the db ,
create table programmatically ..it will work for sure!!!!

Related

How to view the content of .db file?

I am using Xcode 6.4, developing apps for iOS 8 that need to use database. I inserted some information into my database ("something.db" file). I want to see the content of "something.db" to see what I inserted. How can I view its content?
This is my code for creating the database "company.db" and table "Staff"(ID PK, NAME TEXT, AGE INTEGER):
-(void) createOrOpenDB {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
dbPathString = [docPath stringByAppendingPathComponent:#"company.db"];
char *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:dbPathString]) {
const char *dbPath =[dbPathString UTF8String];
if(sqlite3_open(dbPath, &personDB)==SQLITE_OK) {
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS Staff (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER)";
sqlite3_exec(personDB, sql_stmt, NULL, NULL, &error);
sqlite3_close(personDB);
}
}
}
This is my code for inserting information into the table "Staff":
- (IBAction)addPersonButton:(id)sender {
char *error;
if(sqlite3_open([dbPathString UTF8String], &personDB) == SQLITE_OK) {
NSString *insertStmt = [NSString stringWithFormat:#"INSERT INTO Staff (NAME, AGE) values ('%s', '%d')", [self.nameField.text UTF8String], [self.ageField.text intValue]];
const char *insert_stmt = [insertStmt UTF8String];
if(sqlite3_exec(personDB, insert_stmt, NULL, NULL, &error) == SQLITE_OK) {
NSLog(#"Person added");
Person *person = [[Person alloc] init];
[person setName:self.nameField.text];
[person setAge:[self.ageField.text intValue]];
[arrayofPerson addObject:person];
}
sqlite3_close(personDB);
}
}
The code works well because I was able to display the information of the "Staff" table in the tableview. But how to view that information in the .db file?
p/s: I changed it to "something.xls" but Excel does not display human readable information. I also downloaded Fileviewpro but did not know how to use. Someone helps me please!
Thank you very much!
You can use any app that is designed to view the contents of an sqlite file. for example: http://sqlitebrowser.org
If you are running on simulator you can use ~/Library/Developer/CoreSimulator/Devices/1A8DF360-B0A6-4815-95F3-68A6AB0BCC78/data/Container/Data/Application/
to get to the simulator just replace the long UDID with your device.

Sqlite3 database is not executing a query

I am developing an iPhone app in Xcode, I am unable to access the database I have created. Following is the code where I am creating my database
//create local database
NSString *docsDir;
NSArray *dirPaths;
sqlite3 *localDB;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"local.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO) {
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &localDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt1 = "CREATE TABLE IF NOT EXISTS My_choices (perfume_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, na TEXT, got_it TEXT)";
const char *sql_stmt2 = "CREATE TABLE IF NOT EXISTS Ratings (perfume_id INTEGER PRIMARY KEY AUTOINCREMENT, rating NUMERIC)";
const char *sql_stmt3 = "CREATE TABLE IF NOT EXISTS Consultant_Details (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT,website TEXT,domain TEXT,domain_no NUMERIC,phone TEXT,facebook TEXT)";
if (sqlite3_exec(localDB, sql_stmt1, NULL, NULL, &errMsg) != SQLITE_OK) {
NSLog(#"%#",#"Failed to create table My_choices");
}
if (sqlite3_exec(localDB, sql_stmt2, NULL, NULL, &errMsg) != SQLITE_OK) {
NSLog(#"%#",#"Failed to create table ratings");
}
if (sqlite3_exec(localDB, sql_stmt3, NULL, NULL, &errMsg) != SQLITE_OK) {
NSLog(#"%#",#"Failed to create table Consultant_Details");
}
sqlite3_close(localDB);
}
else {
NSLog(#"%#",#"Failed to open/create database");
}
}
add below is the code where I am trying to access it
NSString *docsDir;
NSArray *dirPaths;
sqlite3 *localDB;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
NSString *dbPath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"local.db"]];
NSString *q = #"select * from Ratings where perfume_id in";
q = [q stringByAppendingString:idList];
NSLog(#"%#",q);
const char *sqlStatement2 = [q UTF8String];
sqlite3_stmt *compiledStatement2;
if(sqlite3_open([dbPath UTF8String], &localDB) == SQLITE_OK) {
if(sqlite3_prepare_v2(localDB, sqlStatement2, -1, &compiledStatement2, NULL) == SQLITE_OK) {
NSLog(#"%d", SQLITE_ROW);
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement2) == SQLITE_ROW) {
// Read the data from the result row
int r = sqlite3_column_int(compiledStatement2, 1);
int id = sqlite3_column_int(compiledStatement2, 0);
NSLog(#"%d", id);
for (ListItem *item in self.listItemArray) {
if(item.perfumeId == id){
item.rating = r;
}
}
}
}
else{
NSLog(#"query failed: %s", sqlite3_errmsg(localDB));
}
}
sqlite3_close(localDB);
I always get "query failed No such table exists:Ratings" in my log.
Any help will be appreciated.
Basically this error occured due to unavailabilty of Table in database or wrong query. According to your post, IT look like a error in query.
Query should be something like this:
NSString *q = #"select * from Ratings where perfume_id in ('12','13','14','15')";
Print your "String q" and make sure it follow as above.
Thanks everyone for your help.The database file with the same already existed at that path. So my first method where I was creating a database
if ([filemgr fileExistsAtPath: databasePath ] == NO) check was false and tables were not created.
first remove database file from document directory then use following code to create a sqlite table..
if (![fileManager fileExistsAtPath: _databasePath ])
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_myDataBase) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS My_choices (perfume_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, na TEXT, got_it TEXT);" //TEST
"CREATE TABLE IF NOT EXISTS Ratings (perfume_id INTEGER PRIMARY KEY AUTOINCREMENT, rating NUMERIC);" //USER
"CREATE TABLE IF NOT EXISTS Consultant_Details (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT,website TEXT,domain TEXT,domain_no NUMERIC,phone TEXT,facebook TEXT)"; //METADATA
if (sqlite3_exec(_myDataBase, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create tables");
}
sqlite3_close(_myDataBase);
NSLog(#"DataBase created at: %#",_databasePath);
} else {
NSLog(#"Failed to open/create database");
}
}

Having trouble reading sqlite file

What im trying to do is to read data from my own sqlite file.
My app is allowing me to make a sqlite file and then read from it but if I add the file "asg.sqlite" it wont read from it it only if i have my app create the sqlite file first can i then read from it. Its racking my brain please help here is my code
-(void) createTable: (NSString *) tableName
withField1:(NSString *) field1
withField2:(NSString *) field2
withField3:(NSString *) field3
withField4:(NSString *) field4;
{
char *err;
NSString *sql = [NSString stringWithFormat:
#"CREATE TABLE IF NOT EXISTS '%#' ('%#' "" TEXT PRIMARY KEY, '%#' INTEGER, '%#' INTEGER, '%#' TEXT);", tableName, field1, field2, field3, field4 ];
if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err)
!= SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, #"Could not create table");
} else {
NSLog(#"table created");
}
}
//file path to database
-(NSString *) filePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
return [[paths objectAtIndex:0] stringByAppendingPathComponent:#"asg.sqlite"
];
}
//open the database
-(void)openDB {
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, #"Database failed to open");
}else{
NSLog(#"database opened");
}
}
Bare in mind that if you add you db file in the bundle, it won't be in the Documents directory. You will find it in the main bundle of the app. use
[NSBundle mainBundle] pathForResource:....
This question can help you out

sqlite db creation + objective-c + cordova

I am creating an app in IOS with cordova 2.1.0 framework. I am doing following to create the db:
NSFileManager *fileManager = [NSFileManager defaultManager];
//NSError *error;
if (![fileManager fileExistsAtPath:self.databaseFile]) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.databaseFile = [documentsDirectory stringByAppendingPathComponent:#"klb_db.sqlite"];
[self createConfigTable];
} else {
NSLog(#"fail to create database");
}
// to create config table
-(void) createConfigTable{
NSString *createStmt = #"CREATE TABLE IF NOT EXISTS config (id INTEGER PRIMARY KEY AUTOINCREMENT,key text,value text);";
// Open the database and or create it
if (sqlite3_open_v2([self.databaseFile UTF8String], &databaseHandle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE , NULL) == SQLITE_OK)
{
NSLog(#"database created");
const char *sqlStatement = [createStmt UTF8String];
char *error;
if (sqlite3_exec(databaseHandle, sqlStatement, NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"Config table created.");
}
}
else{
sqlite3_close(databaseHandle);
}
sqlite3_close(databaseHandle);
return;
}
Then, in cordova index.html , i am trying to run a query in the db created above as:
dbName = 'Database';
//to insert username, password into db
db = window.openDatabase(dbName, "1.0", gAppConfig.dbMessage, 200000);
db.transaction(querySelectConfig, errorQuery);
//Get Messages from the DB
function querySelectConfig(tx) {
alert('select config')
tx.executeSql('SELECT * FROM "'+gAppConfig.configTable+'";', [], querySelectSuccess, errorQuery);
}
In the function querySelectConfig(), the query is failing. Why is the query failing. Is the db creation process flawed in objective-c. And secondly, what is the utility of klb_db.sqlite file. When a new database is created, does it need to be blank. And how is .sqlite file created.
Use core data, it will save you time
http://developer.apple.com/library/mac/documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html

cannot insert value to sqlite DB iOS

Well following this tutorial I have some problems in inserting values to my DB although everything seems to be working fine.
This is my code for inserting entries.
-(void)insertOrder:(MyOrderList*)entry
{
// Create insert statement for the person
NSString *insertStatement = [NSString stringWithFormat:#"INSERT INTO LIST (URL, CODE, EMAIL, FULL) VALUES (\"%#\", \"%#\", \"%#\",\"%#\")", entry.db_url, entry.db_code, entry.db_email,entry.db_full];
NSLog(#"SQL INSERTION COMMAND:%#",insertStatement);
char *error;
if ( sqlite3_exec(databaseHandle, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"Order inserted.");
}
else
{
NSLog(#"Error: %s", error);
}
}
And I can see "Order Inserted" being printed out.
This is my code for retrieving the list.
-(NSArray*) getList
{
NSMutableArray *persons = [[NSMutableArray alloc]init];
NSString *queryStatement = [NSString stringWithFormat:#"SELECT URL,CODE ,MAIL, FULL FROM LIST"];
sqlite3_stmt *statement;
NSLog(#"Query:%#",queryStatement);
if (sqlite3_prepare_v2(databaseHandle, [queryStatement UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
// Iterate over all returned rows
while (sqlite3_step(statement) == SQLITE_ROW) {
NSLog(#"Url of my List is:%#",[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)]);
MyOrderList *person = [[MyOrderList alloc]initWithUrl:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)] andCode:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)] andEmail:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 2)] andFull:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 3)]];
[persons addObject:person];
// Release the person because the array takes ownership
//[person release];
}
sqlite3_finalize(statement);
}
//return [persons autorelease];
return persons;
}
and this is how I use it in my .m file
DataController *dataController = [[DataController alloc]init];
[dataController initDatabase];
//[dataController release];
MyOrderList *order = [[MyOrderList alloc] initWithUrl:url_2 andCode:keycode andEmail:mail andFull:full_2 ];
[dataController insertOrder:order];
//data has been added
NSMutableArray* persons = [dataController getList];
and I see that persons are 0.
From terminal I see this:
Admins-MacBook-Air:~ admin$ sqlite3 Users/admin/Library/Application\ Support/iPhone\ Simulator/5.1/Applications/1A70F53B-133E-46AE-833E-13F205EA96EA/Documents/sqlite.db
SQLite version 3.7.12 2012-04-03 19:43:07
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .schema
Error: unable to open database "Users/admin/Library/Application Support/iPhone Simulator/5.1/Applications/1A70F53B-133E-46AE-833E-13F205EA96EA/Documents/sqlite.db": unable to open database file
Admins-MacBook-Air:~ admin$
it's like my db is not even created.
this is my code for creating the DB.
-(void)initDatabase
{
// Create a string containing the full path to the sqlite.db inside the documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"sqlite.db"];
NSLog(#"Path is:%#",databasePath);
// Check to see if the database file already exists
bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:databasePath];
// Open the database and store the handle as a data member
if (sqlite3_open([databasePath UTF8String], &databaseHandle) == SQLITE_OK)
{
// Create the database if it doesn't yet exists in the file system
if (!databaseAlreadyExists)
{
// Create the PERSON table
const char *sqlStatement = "CREATE TABLE IF NOT EXISTS LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, URL TEXT, CODE TEXT, EMAIL TEXT, FULL TEXT)";
char *error;
if (sqlite3_exec(databaseHandle, sqlStatement, NULL, NULL, &error) == SQLITE_OK)
{
NSLog(#"Database and tables created.");
}
else
{
NSLog(#"Error: %s", error);
}
}
}
}

Resources