2012-11-04 124 views
2

如何以编程方式将多行插入到iOS的sqlite3表中?这是我目前的方法的代码片段:在SQLite3中插入多行

sqlite3 *database; 

if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { 
    const char *sqlStatement = "insert into TestTable (id, colorId) VALUES (?, ?)"; 
    sqlite3_stmt *compiledStatement; 

    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
    { 
     for (int i = 0; i < colorsArray.count; i++) { 
      sqlite3_bind_int(compiledStatement, 1, elementId); 
      long element = [[colorsArray objectAtIndex:i] longValue]; 
      sqlite3_bind_int64(compiledStatement, 2, element); 
     } 
    } 

    if(sqlite3_step(compiledStatement) == SQLITE_DONE) { 
     sqlite3_finalize(compiledStatement); 
    } 
    else { 
     NSLog(@"%d",sqlite3_step(compiledStatement)); 
    } 
} 
sqlite3_close(database); 

这样,我只得到了第一行插入,我怎么能告诉我希望每个“for”循环是一个行插入源码?我找不到任何这样的例子...

谢谢!

回答

0

我得到它的工作,这是我现在的代码:

sqlite3 *database; 

if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { 
    const char *sqlStatement = "insert into TestTable (id, colorId) VALUES (?, ?)"; 
    sqlite3_stmt *compiledStatement; 

    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
    { 
     for (int i = 0; i < colorsArray.count; i++) { 
      sqlite3_bind_int(compiledStatement, 1, elementId); 
      long element = [[colorsArray objectAtIndex:i] longValue]; 
      sqlite3_bind_int64(compiledStatement, 2, element); 

      if (sqlite3_step(compiledStatement) == SQLITE_DONE) { 
       if (i == (colorsArray.count - 1)) 
        sqlite3_finalize(compiledStatement); 
       else 
        sqlite3_reset(compiledStatement); 
      } 
      else { 
       NSLog(@"row insertion error"); 
      } 
     } 
    } 
} 
sqlite3_close(database); 
+0

如果最后一次插入失败,该代码会忘记调用'sqlite3_finalize' /'reset'。请不要在'sqlite3_finalize'之前调用'sqlite3_reset'是无害的。 –

+0

明白了,谢谢! –

+0

嗨(int i = 0; i

1

你必须运行此声明:每次插入后

sqlite3_step(compiledStatement) == SQLITE_DONE 

,并在代码中我看到你运行它只有一次,在年底。

+0

谢谢,现在我发现了我失踪了...... –

+0

如果我的回答帮助你解决问题,请将其标记为正确的。 – edzio27