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],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);
// 清空绑定数据
}
if (![self commitTransaction]) {
DLog(@
"提交事务失败
");
return;
}