0
我試圖插入一個數組到SQLite數據庫,我有困難獲取數組變量插入。如何將數組插入SQLite數據庫?
如何從數組中獲取變量(用戶名& fullName)插入到數據庫中?
下面是錯誤信息:
Property 'username' not found on object of type 'NSString *'
Property 'fullName' not found on object of type 'NSString *'
這裏是我的代碼...
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
NSMutableArray *items = result;
sqlite3_stmt *insert_statement;
// prepare the insert statement
const char*sql = "INSERT INTO people (username, fullName) VALUES(?,?)";
sqlite3_prepare_v2(database, sql, -1, &insert_statement, NULL);
// iterate over an array of dictionaries
for (NSString *str in items) {
// NSLog(@"%@",str);
// bind variables
sqlite3_bind_text(insert_statement, 1, [str.username UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insert_statement, 2, [str.fullName UTF8String], -1, SQLITE_TRANSIENT);
// insert fails
if (sqlite3_step(insert_statement) != SQLITE_DONE) {
NSLog(@"Insert failed: %s", sqlite3_errmsg(database));
}
// reset the statement
sqlite3_reset(insert_statement);
}
// release the statement
sqlite3_finalize(insert_statement);
}`
對於什麼是值得的,我強烈建議使用Objective-C sqlite包裝器,如[FMDB](https://github.com/ccgus/fmdb)或[PLDatabase](http://code.google。 com/p/pldatabase /) - 它會讓你的生活更容易 –
首先你的代碼在從數組中獲取用戶名和全名的過程中出錯。我們可以看到後來從未使用過的「str」對象。所以修復你的問題代碼,我們可以幫助)。到目前爲止,你的代碼在sqlite部分看起來不錯。插入前是否成功打開數據庫? – Sergnsk
你得到的錯誤信息是什麼?在這裏發佈項目聲明。你如何創建項目數組?您是否收到錯誤消息「插入失敗:」。?如果是,那麼你的數據庫句柄設置正確。還有一件事要擔心。 – SayeedHussain