c - 使用 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);
换句话说,在高级语言中:
sqlite3_prepare(...)
像cursor.execute(...)
sqlite3_step(...)
像cursor.fetchone(...)
sqlite3_finalize(...)
像这样工作cursor.close(...)
;
这是对这些语句在 sqlite 中如何工作的准确评估吗?sqlite3_exec
获取结果时会使用吗?
解决方案
推荐阅读
- selenium-webdriver - 无法在 selenium 中打开新选项卡或新窗口
- javascript - 在 Nuxt/Vue 应用程序中使用 tawk.to
- javascript - jquery追加不起作用
- c# - 我想编写一个从 json 生成 c# 类对象的工具
- javascript - 防止 alert() 方法触发两次
- c# - 如何在 ASP.NET Web 应用程序中设置表单变量?
- python - 无法通过 python 请求获取真正的 html
- django - Django 数据库迁移错误(sqlite3->postgre)
- javascript - 未处理的承诺拒绝警告。使用 npm run test 运行时的警告
- c# - 使用存储过程时,从具体化的“System.Int32”类型到“System.String”类型的指定转换无效