Reputation: 1219
I have 2 tables on same database.
For first table data is inserted successfully using below code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"test.sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
(sqlite3_exec(database, "BEGIN TRANSACTION", 0, 0, 0))==SQLITE_OK
if ( sqlite3_exec(database, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
{
NSLog(@"------- inserted here ----");
}
else
{
NSLog(@"Error: %s", error);
if(sqlite3_exec(database, "COMMIT", 0, 0, 0) ==SQLITE_OK){
NSLog(@"-------data sucessfully inserted ");
}
else {
NSLog(@"-------data insertion failed");
sqlite3_exec(database, "ROLLBACK", 0, 0, 0);
}
(sqlite3_exec(database, "END TRANSACTION", 0, 0, 0));
sqlite3_close(database);
}
else {
NSLog(@"-------sqlite open error ");
}
The data is inserted successfully as I log.
But when I use the same code for inserting into second table, no data is inserted I get log of
NSLog(@"-------data insertion failed")
I am also opening and closing database at each operation and releasing the handle.
I think sqlite is not allowing me to write on database but don't understand why? Since I have closed database with earlier operation.
Does anyone encountered same problem with no data insertion for 2nd table on same database file.
Addt note: there are no syntax errors and if I don't insert on 1st table then insertion is done on 2nd table which is weird.
Upvotes: 1
Views: 614
Reputation: 6490
Try with this code,
-(NSString*) GetDatabasePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) ;
NSString *documentsDirectory = [paths objectAtIndex:0] ;
return [documentsDirectory stringByAppendingPathComponent:@"test.sqlite"] ;
}
-(void)InsertPurchase
{
sqlite3_stmt *statement=nil;
NSString *path = [self GetDatabasePath];
NSString *query;
if(sqlite3_open([path UTF8String],&db) == SQLITE_OK)
{
query = [NSString stringWithFormat: @"Your insert query"];
if(sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, NULL)
== SQLITE_OK)
{
sqlite3_step(statement);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
Upvotes: 3