Reputation: 63
I'm work in a project where I need to execute a select query(I use sqlite as a sql engine) and load the result into a QTextEdit(I use QT for my graphical interface).
For now I wrote only the following code(but I stuck in the part where I need to append the result to the 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 : %s\n", 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);
}
Maybe I need to operate in the callback function, but I don't know how ... someone can explain it to me?
EDIT:
I have a QTextEdit variable called txtShow, i usually access it by ui->txtShow.insertPlainText("text");
Upvotes: 0
Views: 257
Reputation: 8018
See the synopsis of the sqlite3_exec()
function in the SqlLite documentation:
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 */ );
As you see the 4th parameter is a user defined argument that will be passed to the callback()
function.
So you'll need to use that too interact with your calling code:
//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;
}
When calling the sqlite3_exec()
function pass that:
//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);
}
That's a very common way how C-style API's interact with user code in callback functions.
Upvotes: 1