c++ - 用 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错误,我仍然有同样的问题
谢谢。
解决方案
有几件事,
首先您需要将 error_message 初始化为nullptr
. 否则sqlite3_free
会导致崩溃,因为 error_message 有一些垃圾值。
其次,根据SQLITE 文档,您需要在打开 SQLITE 连接时使用三个选项中的至少一个,
- SQLITE_OPEN_READONLY
- SQLITE_OPEN_READWRITE
- SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
推荐阅读
- python - 如何在 ReportLab Python 中创建内部链接?
- python - 无法从 sklearn MLP 分类器中获得良好的准确性
- mysql - Mysql-如何在病例数达到峰值时获得最大日期
- highcharts - 以角度 8 和 9 将多个高图表导出到单个 pdf
- html - 下拉菜单不下拉
- c# - 如何在 c# WinForms 中正确发送 udp 包?
- reactjs - React Typescript 如何在鼠标输入上工作
- dialogflow-es - Google Assistant 有时会返回 ACTION,有时会返回 TEXT
- javascript - 在角度 7 中隐藏最后添加的 div
- python - discord.py 客户端从服务器踢出用户