2017-08-25 38 views
0

我在一个需要执行选择查询(我使用sqlite作为sql引擎)并将结果加载到QTextEdit(我为图形界面使用QT)的项目中工作。
现在我只写了下面的代码(但我还是坚持在我需要追加结果到的QTextEdit的部分):如何在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); 
} 

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

编辑: 我呼吁txtShow一个QTextEdit变量,我通常ui->txtShow.insertPlainText("text");

+0

您能否使用缩进来正确格式化代码,以便我们可以轻松阅读?而且,你的代码中的任何地方都没有QTextEdit,所以我们不知道在哪里追加。我是否有权假定你想要在QTextEdit中添加printf到终端? – apalomer

回答

1

访问查看sqlite3_exec()功能在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 */ 
); 

正如你看到的第四个参数是用户定义的参数,将被传递给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在回调函数中与用户代码交互。

+0

我有两个错误运行你的代码:第一个是从void到QTextEdit(在回调函数中)的转换......看起来没有一个方法来执行该转换。第二个问题是在第四个参数中(在sqlite3_exec函数中)&myQTextEdit无法识别... – zDoes

+0

@zDoes _“&myQTextEdit无法识别”_您必须将您的QTextEdit控件成员的名称当然。你不能指望你拿我的例子,它开箱即用。这只是解释你的原理是如何工作的。 – user0042

+0

谢谢,我没有看到它......但在回调函数QTextEdit * qTextEdit =(QTextEdit)myQTextEdit;仍然生成铸造错误... – zDoes