Fire Fist
Fire Fist

Reputation: 7050

Cannot insert data into sqlite3 in iOS

I am trying to insert text data into sqlite3 database in iOS.

I wrote following codes to save data into sqlite3 database.

NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MgDB.sqlite"];

        BOOL success = [fileMgr fileExistsAtPath:dbPath];

        if(!success)
        {
            NSLog(@"File Not Found");
        }

        if((!sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK))
        {
            NSLog(@"Error in MyInfo");
        }

        const char *sql = "Insert into MyDB (name,address,email) values('%@','%@','%@')";

        sqlite3_bind_text(sqlStmt, 0, [Name UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(sqlStmt, 1, [Address UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(sqlStmt, 2, [Email UTF8String], -1, SQLITE_TRANSIENT);

        if(sqlite3_prepare(database, sql, -1, &sqlStmt, NULL))
        {
            NSLog(@"Error in Loading database");
        }

        if (sqlite3_exec(database, sql, NULL, NULL, NULL) == SQLITE_OK) 
        {
            return sqlite3_last_insert_rowid(database);
        }


        if(sqlite3_step(sqlStmt) == SQLITE_ROW)
        {
            NSLog(@"ERROR");
        }
    }

    @catch (NSException *exception) 
    {
        NSLog(@"%@",exception);
    }

    @finally 
    {
        sqlite3_finalize(sqlStmt);
        sqlite3_close(database);
    }

according to my above code,I return the last insert ROWID to check that inserted or not.

After saved text data in View,the ROWID have increased.

However when i check my database with FireFox sqlite3 tools, there are no any data that i have inserted.

So i stop running and ReRun my app and add data again.

The last insert ROWID is the same with old count.Not increase even one.

I want to know why it's doesn't save any data into sqlite database.

Is there any problem in my code?

Please help me.

Thanks in advance.

Upvotes: 0

Views: 843

Answers (1)

pmf
pmf

Reputation: 597

NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MgDB.sqlite"];

You can't write to files included in the application bundle. Create (or copy) the database in the Documents directory instead.

See QA1662.

Upvotes: 1

Related Questions