SQLite批量插入的IOS 代码示例(因为使用的是C API,C/C++用法与之类似):
-------------------------代码的分割线-------------------------
// 打开数据库的部分省略
if (![self beginTransaction]) {
DLog(@
"开始事务失败
");
return;
}
sqlite3_stmt* stmt = NULL;
if (sqlite3_prepare(db, [sql UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
NSLog(@"数据库prepareStatment失败:%@", sql);
return;
}
for (Record* record in records) {
int bindPos= 1; // 绑定位置从1开始
if (sqlite3_bind_int(
stmt , (bindPos++),
[record intValue]) != SQLITE_OK) {
NSLog(@
"绑定失败:%@
", [[NSString alloc] initWithUTF8String:sqlite3_errmsg(
db)]);
continue;
}
if (sqlite3_bind_double(
stmt ,
(bindPos++),
[record doubleValue]) != SQLITE_OK) {
NSLog(@
"绑定失败:%@
", [[NSString alloc] initWithUTF8String:sqlite3_errmsg(
db)]);
continue;
}
if (sqlite3_bind_text(
stmt ,
(bindPos++), [
[record stringValue] UTF8String], -1, SQLITE_STATIC) != SQLITE_OK) {
NSLog(@
"绑定失败:%@
", [[NSString alloc] initWithUTF8String:sqlite3_errmsg(
db)]);
continue;
}
if (sqlite3_step(
stmt ) != SQLITE_DONE) { // 执行插入
NSLog(@
"%@
", [[NSString alloc] initWithUTF8String:sqlite3_errmsg(mDB)]);
continue;
}
sqlite3_reset(
stmt );
// 清空绑定数据
}
sqlite3_finalize(
stmt);
if (![self commitTransaction]) {
DLog(@
"提交事务失败
");
return;
}