如何使用 sqlite3 存储到 C++ 变量中?

How do I store into a C++ variables using sqlite3?

我是 C++ 世界的新手。

我正在尝试将我创建的 sqlite table 中包含的值存储到一个变量中,但我不知道该怎么做(我在此处询问之前进行了很多研究)。

所以,在我打开数据库连接后,我执行这个:

   char* sql = new char[4096];
   strcpy(sql, statement.c_str());

   /* Execute SQL statement */
   int rc = sqlite3_exec(DB, sql, callback, 0, &zErrMsg);

   if( rc != SQLITE_OK ){
      fprintf(stderr, "SQL ERROR: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   } else {
      fprintf(stdout, "STATEMENT:\n\n%s\n\nEXECUTED SUCCESSFULLY!\n\n", statement.c_str());
   }

我明白了:

OPENED DATABASE SUCCESSFULLY
sent = 0

sent = 0

sent = 0

sent = 0

sent = 0

sent = 1

sent = 1

sent = 1

STATEMENT:

SELECT sent FROM Message;

EXECUTED SUCCESSFULLY!

我想做的是将 "sent" 中包含的值(数据库中的数据类型是布尔值)存储在一个 int 变量中,我可以操纵它来检查某些条件。或者也许将所有值存储到一个 int 数组中。

我该怎么办?请帮助我!

非常感谢!

编辑: 我正在使用 sqlite3 库。

这是我的回调函数:

static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
   int i;
   for(i = 0; i<argc; i++) {
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
   return 0;
}

callback 是为结果集的每一行调用的函数。您可以将值分配给该函数中的数组或向量。 https://www.sqlite.org/c3ref/exec.html

The 2nd argument to the sqlite3_exec() callback function is the number of columns in the result. The 3rd argument to the sqlite3_exec() callback is an array of pointers to strings obtained as if from sqlite3_column_text(), one for each column. If an element of a result row is NULL then the corresponding string pointer for the sqlite3_exec() callback is a NULL pointer. The 4th argument to the sqlite3_exec() callback is an array of pointers to strings where each entry represents the name of corresponding result column as obtained from sqlite3_column_name().

你需要这样的东西:

int callback(void *p, int size, char **column_text, char **column_name) {
    if (size == 0) return -1;
    auto &container = *static_cast<std::vector<std::string>*>(p);
    if (!column_text[0]) container.push_back("NULL");
    else container.push_back(column_text[0]);
    return 0;
}

然后您可以将这些值存储在您的容器中:

std::vector<std::string> container;
/* Execute SQL statement */
int rc = sqlite3_exec(DB, statement.c_str(), callback, &container, &zErrMsg);

if( rc != SQLITE_OK ){
   fprintf(stderr, "SQL ERROR: %s\n", zErrMsg);
   sqlite3_free(zErrMsg);
} else {
   fprintf(stdout, "STATEMENT:\n\n%s\n\nEXECUTED SUCCESSFULLY!\n\n", statement.c_str());
}

不要将 sqlite3_exec() 用于任何需要对查询结果执行任何操作的操作,或任何涉及用户提供的值的操作。使用 prepared statement.

类似

sqlite3_stmt *stmt;
int rc = sqlite3_prepare_v2(DB, statement.c_str(), statement.length(), &stmt, nullptr);
if (rc != SQLITE_OK) {
 // handle the error
}
// Loop through the results, a row at a time.
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
 int sent = sqlite3_column_int(stmt, 0);
 // etc.
}
// Free the statement when done.
sqlite3_finalize(stmt);