[英]SQLite3 is not writing table creations to the database
我目前正在努力解決一個在我看來像是一種回歸的問題,因為我以前沒有經歷過它。
支持以下程序來創建 SQLite3 數據庫、名為sample
的新表,並用單行填充它。
#include <sqlite3.h>
#include <stdio.h>
int main() {
int rc;
sqlite3_stmt* stmt;
sqlite3* db;
rc = sqlite3_open("/tmp/test_second.db", &db);
if (rc) {
printf("Failed to open sqlite3 database: %s\n", sqlite3_errmsg(db));
return 1;
}
rc = sqlite3_prepare_v2(db, "CREATE TABLE sample (anum INTEGER PRIMARY KEY); ", -1, &stmt, NULL);
if (rc != SQLITE_OK) {
printf("Failed to create table: %s\n", sqlite3_errmsg(db));
return 1;
}
sqlite3_finalize(stmt);
rc = sqlite3_prepare_v2(db, "INSERT INTO sample (anum) VALUES (0); ", -1, &stmt, NULL);
if (rc != SQLITE_OK) {
printf("Failed to insert row: %s\n", sqlite3_errmsg(db));
return 1;
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return 0;
}
I have compiled this on two different environments: CentOS 7.9 with GCC 4.8.5 and SQLite 3.7.17, and Ubuntu 20.04.5 LTS with GCC 9.4.0 and SQLite 3.31.1.
在這兩種環境下,編譯和運行程序都會出現以下錯誤:
Failed to insert row: no such table: sample
並且數據庫是一個零長度文件,里面沒有表。 但是,將這些 SQL 語句直接粘貼到 sqlite3 shell 中可以完美地工作。 代碼有什么問題?
您只是在准備要運行的語句,但您沒有使用sqlite3_step()
function 運行它們。
該流程寫在SQLite C 接口文檔的介紹中。
對於您的兩個 static SQL 語句,方便的包裝器sqlite3_exec()
可以正常工作:
#include <sqlite3.h>
#include <stdio.h>
int main() {
int rc = 0;
sqlite3 *db;
rc = sqlite3_open("/tmp/test_second.db", &db);
if (rc) {
printf("Failed to open sqlite3 database: %s\n", sqlite3_errmsg(db));
return 1;
}
rc = sqlite3_exec(db, "CREATE TABLE sample (anum INTEGER PRIMARY KEY); ", NULL, NULL, NULL);
if (rc != SQLITE_OK) {
printf("Failed to create table: %s\n", sqlite3_errmsg(db));
return 1;
}
rc = sqlite3_exec(db, "INSERT INTO sample (anum) VALUES (0); ", NULL, NULL, NULL);
if (rc != SQLITE_OK) {
printf("Failed to insert row: %s\n", sqlite3_errmsg(db));
return 1;
}
sqlite3_close(db);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.