首页 > 解决方案 > 使用 sqlite 获取数据

问题描述

我一直在尝试使用这里的 SQLite 教程来学习如何在 C 中使用 SQLite。我在弄清楚如何使用它时遇到了麻烦,因为它只提到了sqlite3_exec,这对于基本查询来说似乎非常不直观(它对所有内容都使用回调)。然后我遇到了这个答案,https://stackoverflow.com/a/31168999/11954200,它解决了同样的问题,并建议使用基本上合并到sqlite3_exec速记形式中的各种四个 sqlite 语句。到目前为止,这是我的理解:

// Query to get the rows

// Part1 -- Prepare the query: cursor.execute()
// http://www.sqlite.org/c3ref/prepare.html
sqlite3_stmt *stmt; // this is the prepared statement that the sqlite3_prepare writes to
rc = sqlite3_prepare(db, "SELECT * FROM mytable LIMIT 20", -1, &stmt, NULL);
if (rc != SQLITE_OK) {
    printf("error: %s", sqlite3_errmsg(db));
    return 0;
}


// Part2 -- equivalent of cursor.fetchone()
// http://www.sqlite.org/c3ref/step.html
int rownum=1;
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {

    // Part3 -- reference the values from the row
    // http://www.sqlite.org/c3ref/column_blob.html
    int id                       = sqlite3_column_int(stmt, 0);
    const unsigned char * date   = sqlite3_column_text(stmt, 1);
    printf("Row: %d | ID: %d | Date: %s\n", rownum, id, date);
    rownum++;
}

// Part4 -- equivalent of cursor.close()
// http://www.sqlite.org/c3ref/finalize.html
sqlite3_finalize(stmt);

换句话说,在高级语言中:

这是对这些语句在 sqlite 中如何工作的准确评估吗?sqlite3_exec获取结果时会使用吗?

标签: csqlite

解决方案


推荐阅读