gpt4 book ai didi

iphone - 如何将数组插入到 SQLite 数据库中?

转载 作者:行者123 更新时间:2023-11-28 23:13:37 26 4
gpt4 key购买 nike

我正在尝试将数组插入到 SQLite 数据库中,但在插入数组变量时遇到了困难。

如何从数组(用户名和全名)中获取变量以插入到数据库中?

错误信息如下:

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);
}`

最佳答案

此代码与启动事务和提交事务结合使用效果很好:

// 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);

关于iphone - 如何将数组插入到 SQLite 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7342067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com