首页 > 解决方案 > 用 C++ 创建一个 sqlite3 表

问题描述

我知道他们是另一个具有这个确切标题的问题,但它并没有解决我的问题,所以就这样吧。

我正在关注有关在 c++ 中使用 SQLite 的教程,但是当我运行程序来创建数据库表时,出现错误;

static int create_database(const char *s);
static int create_table(const char *s);

int main(){
    const char *file = "Mafia.sqlite";
    sqlite3 *db;

    create_database(file);
    create_table(file);
}

static int create_database(const char* s){
    sqlite3 *db = NULL;
    int query = 0;

    query = sqlite3_open_v2(s, &db, SQLITE_OPEN_CREATE, NULL);
    cout << "Database created successfully!\n";
    sqlite3_close(db);

    return 0;
}

static int create_table(const char* s){
    sqlite3 *db;

    string sql = "CREATE TABLE IF NOT EXISTS USERS("
                "ID INTEGER PRIMARY KEY AUTOINCREMENT,"
                "USERNAME TEXT NOT NULL,"
                "PASSWORD TEXT NOT NULL);";

    try{
       int query = 0;
       query = sqlite3_open_v2(s, &db, SQLITE_OPEN_READWRITE, NULL);

       char *error_message;
       query = sqlite3_exec(db, sql.c_str(), NULL, 0, &error_message);

       if(query != SQLITE_OK){
           cerr << "Error occurred creating table!\n";
           sqlite3_errmsg(db);
           sqlite3_free(error_message);
       }else
           cout << "Table created successfully\n";
       sqlite3_close(db);
    }
    catch(const exception &e){
        cerr << e.what() << '\n';
    }

}

我的终端返回以下内容:

Database created successfully!
Error occurred creating table!
test(13698,0x109148dc0) malloc: Non-aligned pointer 0x102bd9641 being freed
test(13698,0x109148dc0) malloc: *** set a breakpoint in malloc_error_break to debug

编辑 我纠正了sql错误,我仍然有同样的问题

谢谢。

标签: c++sqlite

解决方案


有几件事,

首先您需要将 error_message 初始化为nullptr. 否则sqlite3_free会导致崩溃,因为 error_message 有一些垃圾值。

其次,根据SQLITE 文档,您需要在打开 SQLITE 连接时使用三个选项中的至少一个,

  1. SQLITE_OPEN_READONLY
  2. SQLITE_OPEN_READWRITE
  3. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
您不应该使用 SQLITE_OPEN_CREATE 作为独立选项。如果你改变这两个,它应该可以正常工作。


推荐阅读