ios - Insert data into sqlite database -
i'm insert data sqlite database , i've seen nslog(@"done") on console result, don't see data update in sqlite database file. pls me !!!
here code save data:
- (void)savedata:(nsstring *)_id { sqlite3_stmt *statement; nsstring *_databasepath = [[[nsbundle mainbundle] resourcepath ]stringbyappendingpathcomponent:@"data.db"]; const char *dbpath = [_databasepath utf8string]; if (sqlite3_open(dbpath, &db) == sqlite_ok) { nsstring *insertsql = [nsstring stringwithformat: @"insert mytable (id) values (\"%@\")", _id]; const char *insert_stmt = [insertsql utf8string]; sqlite3_prepare_v2(db, insert_stmt, -1, &statement, null); if (sqlite3_step(statement) == sqlite_done) { nslog(@"done"); } else { nslog(@"failed add contact"); } sqlite3_finalize(statement); sqlite3_close(db); } }
you opening database in bundle. bundle read-only on device. must copy database documents
folder (if doesn't exist there already) , open there.
also aware you're dealing multiple copies of database (the 1 in project, 1 in bundle , 1 in device/simulator's documents
folder). make sure you're checking inserted record in correct database (the 1 in documents
)
as aside, should check see sqlite3_prepare_v2
returned sqlite_ok
, if not, log sqlite3_errmsg
.
you should use ?
placeholder in sql , bind values using sqlite3_bind_text
(or, if it's possibly nil
, sqlite_bind_null
):
- (void)savedata:(nsstring *)_id { sqlite3_stmt *statement; nsstring *bundlepath = [[[nsbundle mainbundle] resourcepath ] stringbyappendingpathcomponent:@"data.db"]; nsstring *documentsfolder = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes)[0]; nsstring *documentspath = [documentsfolder stringbyappendingpathcomponent:@"data.db"]; nsfilemanager *filemanager = [nsfilemanager defaultmanager]; if (![filemanager fileexistsatpath:documentspath isdirectory:no]) { nserror *error; if (![filemanager copyitematpath:bundlepath topath:documentspath error:&error]) { nslog(@"database copy failed: %@", error); } } const char *dbpath = [documentspath utf8string]; if (sqlite3_open(dbpath, &db) == sqlite_ok) { const char *insertsql = "insert mytable (id) values (?)"; if (sqlite3_prepare_v2(db, insertsql, -1, &statement, null) != sqlite_ok) { nslog(@"prepare error: %s", sqlite3_errmsg(db)); } // bind value ? placeholder in sql if (_id) { if (sqlite3_bind_text(statement, 1, [_id utf8string], -1, sqlite_transient) != sqlite_ok) { nslog(@"bind text error: %s", sqlite3_errmsg(db)); } } else { if (sqlite3_bind_null(statement, 1) != sqlite_ok) { nslog(@"bind null error: %s", sqlite3_errmsg(db)); } } if (sqlite3_step(statement) == sqlite_done) { nslog(@"done"); } else { nslog(@"failed add contact: %s", sqlite3_errmsg(db)); } sqlite3_finalize(statement); sqlite3_close(db); } }
most people move "if database doesn't exist in documents, copy bundle , open there" logic inside dedicated opendatabase
method, illustrates idea.
Comments
Post a Comment