我在下面粘贴了我的代码。它在sqlite3_get_table()中给出了seg错误。我想获取表中的行数并返回该行。如果行数大于0,则程序需要读取所有行。
int countRowsInTable() {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char const *sql;
char ***pazResult;
int *pnRow; /* Number of result rows written here */
int *pnColumn; /* Number of result columns written here */
rc = sqlite3_open("DeviceDetails.db", &db);
if( rc )
{
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
}
else
{
fprintf(stderr, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "select * from Device_Details";
/* Execute SQL statement */
// rc = sqlite3_exec(db, sql, 0/*callback*/, 0/*(void*)data*/, &zErrMsg);
rc = sqlite3_get_table(db, sql, pazResult, pnRow, pnColumn, &zErrMsg);
void sqlite3_free_table(char **result);
if( rc != SQLITE_OK )
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else
{
fprintf(stdout, "Operation done successfully\n");
cout<<"rows="<<pnRow<<endl;
sleep(10);
}
sqlite3_close(db);
cout<<"num rows =" << *pnRow <<endl;
}
阅读完你的建议后,我改变了我的代码。现在我使用select count(*),但where(which)变量将保存行数。我需要在sqlite3_exec中实现回调函数。如果行数大于零,我还需要获取数据。如果我在回调函数中获取数据,如何将它传递给调用表中的countRows函数?也许我可以保留一个全局变量。一旦执行回调,它将通过条件变量发出调用函数的信号。所以我必须在新线程中维护countRowsInTable函数。我有更简单的方法吗?
int countRowsInTable()
{
sqlite3 *db;
char *zErrMsg = new char[64];
int rc;
char const *sql;
char ***pazResult;
int *pnRow = new int; /* Number of result rows written here */
int *pnColumn = new int; /* Number of result columns written here */
//*pnRow = 0;
**pazResult = new char[20480];
rc = sqlite3_open("DeviceDetails.db", &db);
if( rc )
{
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
}
else
{
fprintf(stderr, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "select count(*) from Device_Details";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, 0/*callback*/, 0/*(void*)data*/, &zErrMsg);
//rc = sqlite3_get_table(db, sql, pazResult, pnRow, pnColumn, &zErrMsg);
//void sqlite3_free_table(char **result);
if( rc != SQLITE_OK )
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else
{
fprintf(stdout, "Operation done successfully\n");
}
}
答案 0 :(得分:1)
您没有使用正确的参数调用该函数。您正在传递未初始化的指针,而您必须创建变量并传递指针,以便SQLite可以写入值。
const char *sql = "select * from Device_Details";
char **result;
int nrow;
int ncolumn;
char *errmsg;
int rc;
rc = sqlite3_get_table(db, sql, &result, &nrow, &ncolumn, &errmsg);
但是,您应该知道SQLite手册不鼓励使用该功能:“这是为了向后兼容而保留的旧版界面。不建议使用此界面。”
此外,您应该删除可能错误粘贴的void sqlite3_free_table(char **result)
。