如何在 QTextEdit 面板中附加选择查询结果?

How to append select query results in a QTextEdit panel?

本文关键字:选择 查询 结果 QTextEdit      更新时间:2023-10-16

我正在一个项目中工作,我需要执行一个选择查询(我使用 sqlite 作为 sql 引擎(并将结果加载到 QTextEdit 中(我使用 QT 作为我的图形界面(。
现在我只写了以下代码(但我卡在我需要将结果附加到 QTextEdit 的部分(:

//Callback function to print the query to the console
int db_files::CallBack(void *notUsed, int argc, char **argv, char **azColName) {
for(int i = 0; i<argc; i++) {
printf("%s : %sn", azColName[i], argv[i] ? argv[i] : "NULL");
}
std::cout << "n";
return 0;
}
//Function where I open the database and run the query
void custHandler::show_all() {
rc = sqlite3_open("database.db", &db);
if(rc != SQLITE_OK) {
sqlite3_close(db);
exit(1);
}
sqlCust = "SELECT * FROM DB";
rc = sqlite3_exec(db, sqlCust, CallBack, 0, &ErrMsg);
if (rc != SQLITE_OK) {
exit(1);
}
sqlite3_free(ErrMsg);
sqlite3_close(db);
}

也许我需要在回调函数中操作,但我不知道如何...有人可以给我解释一下吗?

编辑: 我有一个名为txtShow的QTextEdit变量,我通常通过以下方式访问它ui->txtShow.insertPlainText("text");

请参阅 SqlLite 文档中sqlite3_exec()函数的概要:

int sqlite3_exec(
sqlite3*,                                  /* An open database */
const char *sql,                           /* SQL to be evaluated */
int (*callback)(void*,int,char**,char**),  /* Callback function */
void *,                                    /* 1st argument to callback */
char **errmsg                              /* Error msg written here */
);

如您所见,第 4 个参数是用户定义的参数,将传递给callback()函数。

因此,您还需要使用它与调用代码进行交互:

//Callback function to print the query to the console
int db_files::CallBack(void *myQTextEdit, int argc, char **argv, char **azColName) {
QTextEdit* qTextEdit = (QTextEdit*)myQTextEdit;
for(int i = 0; i<argc; i++) {
// Add the results to qTextEdit as needed ...
}
return 0;
}

调用sqlite3_exec()函数时,传递:

//Function where I open the database and run the query
void custHandler::show_all() {
rc = sqlite3_open("database.db", &db);
if(rc != SQLITE_OK) {
sqlite3_close(db);
exit(1);
}
sqlCust = "SELECT * FROM DB";
rc = sqlite3_exec(db, sqlCust, CallBack, &myQTextEdit, &ErrMsg);
// ^^^^^^^^^^^^
if (rc != SQLITE_OK) {
exit(1);
}
sqlite3_free(ErrMsg);
sqlite3_close(db);
}

这是 C 样式 API 与回调函数中的用户代码交互的一种非常常见的方式。