gpt4 book ai didi

C++ MFC SQLite sqlite3_exec 回调

转载 作者:行者123 更新时间:2023-11-28 05:33:43 25 4
gpt4 key购买 nike

所以我正在尝试在 Visual Studio 2010 中将 SQLite 与 MFC 对话一起使用。我不清楚如何使用回调函数来保存查询结果,该查询试图计算表的数量在我的数据库中,进入变量 m_Results。有没有办法做到这一点,或者有没有办法让我访问 nTables 变量?

static int callback(void *data, int argc, char **argv, char **azColName){
int i;
fprintf(stderr, "%s: ", (const char*)data);
data = argv[0];
return 0;
}

BOOL CDBpracticeDlg::OnInitDialog(){
...

// TODO: Add extra initialization here
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called";

rc = sqlite3_open("structInfo_Test.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(*) as nTables FROM sqlite_master where type='table';";

/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, &m_Results, &zErrMsg);
if( rc != SQLITE_OK ){
char error[200];
strcpy(error,"SQL error: ");
strcat(error,zErrMsg);
m_Results = error;
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}else{
fprintf(stdout, "Operation done successfully\n");
}
UpdateData(FALSE);
sqlite3_close(db);

return TRUE; // return TRUE unless you set the focus to a control
}

最佳答案

sqlite3_exec 的回调API 被广泛记录在案。据称它具有误导性的参数名称这一事实也无济于事。提供更自然的形式参数名称大有帮助:

static int callback(void* context,  // user-provided object (4th param to sqlite3_exec)
int columnCount, // number of columns
char** columnValues, // array of column values as C-style strings
char** columnName) // array of column names as C-style strings

要从 回调 更新 m_Results 对象,您只需将 context 转换为正确的类型,然后使用它:

static int callback(void* context, int columnCount,
char** columnValues, char** columnNames) {
CMyType& results = *static_cast<CMyType*>(context);
// Use 'results' which is a reference to 'm_Results'.
for (int index = 0; index < columnCount; ++index) {
// Assuming CMyType has operator+=(const char*) (like a CString)
results += columnNames[index];
results += ": ";
results += columnValues[index];
}
// Return 0 to continue invoking the callback for the remaining rows in the result
// set. Returning non-zero will terminate the callbacks, and sqlite3_exec()
// returns SQLITE_ABORT.
return 0;

作为替代方案,您可以将 this 代替 &m_Results 传递给 sqlite3_exec(),并从回调中调用公共(public)类成员:

static int callback(void* context, int columnCount,
char** columnValues, char** columnNames) {
CDBpracticeDlg* obj = static_cast<CDBpracticeDlg*>(context);
// Delegate callback to class member implementation
return obj->MyCallback(columnCount, columnValues, columnNames);
}

...

rc = sqlite3_exec(db, sql, callback, this, nullptr);

关于C++ MFC SQLite sqlite3_exec 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38825480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com