I tried to implement to insert data to sqlite database in many ways. In run time, the code executed returns the id that is inserted but when I check the database, nothing is inserted. Does anyone know what is the problem? Many thanks in advance.
The code I implemented here:
sqlite3 *database;
sqlite3_stmt *addStmt;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"MoviePlayerMgmt.rdb"];
BOOL success =[fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(@"Cannot locate file %@",dbPath);
}
else{
NSLog(@"__________Open the file__________ %@",dbPath);
if(!(sqlite3_open([dbPath UTF8String], &database)==SQLITE_OK))
{
NSLog(@"An error has occured: %@",[NSString stringWithUTF8String:(char *) sqlite3_errmsg(database)]);
}
else{
NSLog(@"Open database");
NSString *strName = txtName.text;
NSLog(@"Computer name is %@",strName);
NSString *strIP = txtIP.text;
NSString *strPort = txtPort.text;
NSString *insertStatement = [NSString stringWithFormat:@"INSERT INTO COMPUTER (computerName, IPAddress, portNumber) VALUES (\"%@\", \"%@\", \"%@\")", strName, strIP, strPort];
char *error;
if ( sqlite3_exec(database, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
{
int computerID = sqlite3_last_insert_rowid(database);
NSLog(@"A computer inserted. %d",computerID);
sqlite3_close(database);
}
else
{
NSLog(@"Error: %s", error);
}
}
}
An app’s resource bundle is read-only (at least on a real iOS device). You can’t write to a database in the app’s resource bundle.
The first time your app is run, you need to copy the initial database from the app’s bundle to another, writable directory in the app’s sandbox. Then you always use this copy for reading and writing.
Edit:
You should also change your use of
sqlite3_opentosqlite3_open_v2. This gives you a bit more control.Also, do not create queries like your insert statement using string formats. You should create the query with a ? symbol for each variable. Then use the appropriate
sqlite3_bind_xxxfunctions to bind the proper value to the statement. This will ensure values are properly escaped.