简体   繁体   English

使用 c++ 创建一个 sqlite3 表

[英]Creating an sqlite3 table with c++

I know their is another question with this exact title but it doesn't solve my problem, so here goes.我知道他们是另一个具有这个确切标题的问题,但它并没有解决我的问题,所以就这样吧。

I am following a tutorial on using SQLite with c++, but when I run my program to create the database table, I get an error;我正在关注有关将 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';
    }

}

My terminal returns the following:我的终端返回以下内容:

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

Edit I corrected the sql error and I still have the same problem编辑我纠正了 sql 错误,我仍然有同样的问题

Thanks.谢谢。

There are couple of things,有几件事,

First you need to initialize error_message to nullptr .首先,您需要将 error_message 初始化为nullptr Otherwise sqlite3_free will cause a crash since error_message is having some garbage value.否则sqlite3_free将导致崩溃,因为 error_message 有一些垃圾值。

Secondly, according to the SQLITE documentation , you need to use atleast one of the three options while opening an SQLITE connection,其次,根据SQLITE 文档,您需要在打开 SQLITE 连接时使用三个选项中的至少一个,

  1. SQLITE_OPEN_READONLY SQLITE_OPEN_READONLY
  2. SQLITE_OPEN_READWRITE SQLITE_OPEN_READWRITE
  3. SQLITE_OPEN_READWRITE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE SQLITE_OPEN_CREATE
You are not supposed to use SQLITE_OPEN_CREATE as a standalone option. 您不应该使用 SQLITE_OPEN_CREATE 作为独立选项。 If you change these two, it should work fine. 如果你改变这两个,它应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM