当我在c ++中使用一个函数来初始化sqlite3时,当它从函数中出来时,句柄是Null。知道是什么原因引起的吗?我只需将指针作为参数。如果我将open打开到main函数,它可以正常工作。会发生什么导致这个?隐藏的内容是否超出了范围?
#include <iostream>
#include "sqlite3.h"
using namespace std;
int init_table(sqlite3 *dbH, string db_name)
{
if (sqlite3_open(db_name.c_str(), &dbH) != SQLITE_OK)
{
cout << "Failed to open DB : " << sqlite3_errmsg(dbH) << endl;
abort();
}
else
{
cout << "Opened database: " << db_name << endl;
}
if (sqlite3_exec(dbH, "PRAGMA synchronous = OFF", NULL, NULL, NULL) != SQLITE_OK)
{
cout << "Failed to set synchronous: " << sqlite3_errmsg(dbH) << endl;
}
if (sqlite3_exec(dbH, "PRAGMA journal_mode = WAL", NULL, NULL, NULL) != SQLITE_OK)
{
cout << "Failed to set journal mode: " << sqlite3_errmsg(dbH) << endl;
}
cout << "dbH 2: " << dbH << endl;
}
int main()
{
sqlite3 * dbH;
dbH = NULL;
cout << "dbH 1: " << dbH << endl;
string dbName = "foo1.db";
init_table(dbH, dbName);
cout << "dbH 3: " << dbH << endl;
}
运行时
$ ./a.out
dbH 1: 0
Opened database: foo1.db
dbH 2: 0x5baa048
dbH 3: 0
答案 0 :(得分:3)
应该是
int init_table(sqlite3 **dbH, string db_name)
并将指针传递给指针?
可能是sqliter处理没有问题。它既可以将指针作为引用传递,也可以作为指针传递指针。
当然,在通过时,您需要在修改后将&dbH
传递给init_table
。