使用c ++创建sqlite3表

问题描述 投票:0回答:1

我知道他们是另一个与此标题完全相同的问题,但这不能解决我的问题,所以去吧。

我正在学习将SQLite与c ++结合使用的教程,但是当我运行程序来创建数据库表时,出现错误;

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
1个回答
0
投票

有几件事,首先,您需要将error_message初始化为nullptr。否则sqlite3_free将导致崩溃,因为error_message具有某些垃圾值。其次,根据SQLITE documentation,您需要在打开SQLITE连接时至少使用三个选项之一,

  1. SQLITE_OPEN_READONLY
  2. SQLITE_OPEN_READWRITE
  3. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
您不应将SQLITE_OPEN_CREATE用作独立选项。如果您更改这两个,它应该可以正常工作。
© www.soinside.com 2019 - 2024. All rights reserved.