Reputation: 7444
I am currently trying to simply insert a new row into my SQLite3 database on my iPad. I have done it multiple times before in other apps and just copied the code. The copied SELECT
queries work fine, but if I try to INSERT
, it fails at == SQLITE_DONE
This is how I try to insert into the database:
NSString *databaseName = @"Waypoints.sql";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
sqlite3 *database;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSString *statement = [NSString stringWithFormat:
@"INSERT INTO Waypoints (id, name, alt, ias, temp, tas, wd, ws, gs, mt, mh, dist, time, fuel, fuelrate) VALUES (%d,'New...','','','','','','','','','','','','','');", [self numberOfWaypoints]];
NSLog(@"Statement: %@", statement);
const char *sqlStatement = [statement cStringUsingEncoding:NSASCIIStringEncoding];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
if(sqlite3_step(compiledStatement) == SQLITE_DONE)
NSLog(@"DATABASE: Adding: Success");
else
NSLog(@"DATABASE: Adding: Failed");
}
else
NSLog(@"Error. Could not add Waypoint.");
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
If I run this code on the press of a button, it outputs DATABASE: Adding: Failed
in the console.
The NSLogged statement looks like this:
INSERT INTO Waypoints (id, name, alt, ias, temp, tas, wd, ws, gs, mt, mh, dist, time, fuel, fuelrate) VALUES (2,'New...','','','','','','','','','','','','','');
Which works perfectly fine if I paste it in the terminal (connected to same database file).
This brings me to the conclusion: what could be causing this problem?
I thought of maybe write permissions to the file. Could be it, but it's not in the bundle but already copied to the documents folder on the device.
Please help to how I can get this to work?
Upvotes: 1
Views: 938
Reputation: 2605
Try using NSUTF8StringEncoding for your cStringUsingEncoding or printing
NSLog(@"%@", [NSString stringWithUTF8String:(char*)sqlite3_errmsg(database)]);
Glad to see you could find your error with this.
Upvotes: 2
Reputation: 7444
By following the tip from @IgnacioInglese by printing out the error with NSLog(@"%@", [NSString stringWithUTF8String:(char*)sqlite3_errmsg(database)]);
I found that the database is locked.
I found that I made a rookie-error by return a value in a method before closing the database. Fixing that solved my problem.
Upvotes: 0