简体   繁体   English

如何将数组写入Objective-C的sqlite数据库?

[英]How to write the array into the sqlite database for Objective-C?

I have taken the data from database into array now I want it to send it back into database by using the insert query. 我已经将数据库中的数据转换为数组,我希望它使用insert查询将其发送回数据库。

How can I insert the array of the data into the database? 如何将数据数组插入数据库?

Inserting into the database is pretty much the reverse of reading from it. 插入数据库几乎与从中读取数据相反。 You don't say what the structure of your array is but here is some skeleton code you should be able to adapt to your needs: 你没有说你的数组的结构是什么,但这里有一些骨架代码,你应该能够适应你的需求:

// Assuming you have the sqlite database opened already
// sqlite3 *sqldb = ...;

// Also assuming you have an array of MyItems holding your data
// NSMutableArray *items = ...;

sqlite3_stmt *insert_statement;

// Prepare the insert statement
const char*sql = "INSERT INTO mytable (field1, field2, field3) VALUES(?,?,?)";
sqlite3_prepare_v2(sqldb, sql, -1, &insert_statement, NULL);

// Iterate over an array of dictionaries
for (MyItem *item in items) {

    // Bind variables - assumed to all be integers
    sqlite3_bind_int(insert_statement, 1, item.field1);
    sqlite3_bind_int(insert_statement, 2, item.field2);
    sqlite3_bind_int(insert_statement, 3, item.field3);

    // Execute the insert
    if (sqlite3_step(insert_statement) != SQLITE_DONE) {
        NSLog(@"Insert failed: %s", sqlite3_errmsg(sqldb));
    }

    // Reset the statement
    sqlite3_reset(insert_statement);
}

// release the statement
sqlite3_finalize(insert_statement);

迭代数组的内容并构建INSERT查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM