2011-09-08 35 views
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); 
}` 
+1

对于什么是值得的,我强烈建议使用Objective-C sqlite包装器,如[FMDB](https://github.com/ccgus/fmdb)或[PLDatabase](http://code.google。 com/p/pldatabase /) - 它会让你的生活更容易 –

+0

首先你的代码在从数组中获取用户名和全名的过程中出错。我们可以看到后来从未使用过的“str”对象。所以修复你的问题代码,我们可以帮助)。到目前为止,你的代码在sqlite部分看起来不错。插入前是否成功打开数据库? – Sergnsk

+0

你得到的错误信息是什么?在这里发布项目声明。你如何创建项目数组?您是否收到错误消息“插入失败:”。?如果是,那么你的数据库句柄设置正确。还有一件事要担心。 – SayeedHussain

回答

2

该代码可以使用启动事务,并承诺得很好OK组合:

// start transaction 
sqlite3_stmt *begin_transaction_stmt; 
const char *beginTrans = "BEGIN EXCLUSIVE TRANSACTION"; 

if (sqlite3_prepare_v2(database, beginTrans, -1, &begin_transaction_stmt, NULL) != SQLITE_OK) { 
    sqlite3_close(database); 
    return NO; 
} 

sqlite3_step(begin_transaction_stmt); 
sqlite3_finalize(begin_transaction_stmt); 

========== [你的帖子上面的代码来这里] =============

// commit transaction 
sqlite3_stmt *end_transaction_stmt; 
const char *endTrans = "COMMIT"; 
if (sqlite3_prepare_v2(database, endTrans, -1, &end_transaction_stmt, NULL) != SQLITE_OK) { 
    sqlite3_close(database); 
    return NO; 
} 

sqlite3_step(end_transaction_stmt); 
sqlite3_finalize(end_transaction_stmt);