我正在使用Visual Studio 2015,基本上我想从sqlite数据库中检索一些数据并将其存储在字符串中。
以下代码仅在屏幕上显示数据,是否有任何方法可以将其存储在字符串中。
PS:我已经通过命令提示符创建了表。

 int main()
 {
   char *zErrMsg = 0;
   sqlite3 *db;
   int rc;
   rc = sqlite3_open("testingvisual.db", &db);

    //string sql;
    char *data;
  const char *sql;
  sql = "INSERT INTO TESTDATA VALUES (1,'test','test2');";
    sqlite3_exec(db, sql, callback, 0, &zErrMsg);
    sql = "SELECT * FROM TESTDATA WHERE id=1;";
   sqlite3_exec(db, sql, callback, 0, &zErrMsg);
  }

最佳答案

当您希望检索数据(即处理SELECT语句)时,请使用API​​ sqlite3_prepare_v2和sqlite3_step。如您所见,sqlite3_exec是处理INSERT,UPDATE,DELETE和数据定义函数的正确选择。这是SELECT查询的入门入门粗略处理:

sqlite3_stmt* t_statement;
sql="SELECT * FROM TESTDATA WHERE id=1;";
size_t t_len = strlen(sql);

int rc = sqlite3_prepare_v2(db, sql, t_len, &t_statement, &zErrMsg);

if (rc == SQLITE_OK)
{
   rc = sqlite3_step(t_statement);
   if (rc == SQLITE_OK)
   {
       // iterate over the columns to get the data
       const char* t_value =
          sqlite3_column_text(t_statement, [column_number]);
   }
}
else
{
    // zErrMsg may have an error message. If not, the database object
    // may have one. Either way, you can find out what went wrong.
    const char* db_error_msg = sqlite3_errmsg(db);
}


我将浏览器书签设置为https://www.sqlite.org/c3ref/funclist.html。 FWIW,我建立了一个类来管理SQLite交互,以便我的代码可以对SQLite API函数(例如ExecSQL(),SetIsActive(),FetchNext(),GetFieldByName()等)进行友好的调用。您可能也想做类似的事情。

10-07 16:46
查看更多