我想像这样从 abe_account 中选择 *
sqlite> select * from abe_account;
admin|Peter John|admin_account|password
Run Code Online (Sandbox Code Playgroud)
但我想在 C++ 中做到这一点并返回每个元素,例如
admin as vector x[0]
Peter John as vector x[1]
admin_account as vector x[2]
password as vector x[4]
Run Code Online (Sandbox Code Playgroud)
然后在我关闭 sqlite3_close(db) 时在外面使用它
如 cout << x[0] << endl;
我该怎么做,我试图 cout << str << endl;
但它什么也不打印。
下面的代码是我自己尝试的:
#include <iostream>
#include <sqlite3.h>
//g++ -o test test.cpp -lsqlite3
using namespace std;
int main()
{
sqlite3 *db;
sqlite3_stmt * stmt;
if (sqlite3_open("abeserver.db", &db) == SQLITE_OK)
{
sqlite3_prepare( db, "SELECT * from abe_account;", -1, &stmt, NULL );//preparing the statement
sqlite3_step( stmt );//executing the statement
char * str = (char *) sqlite3_column_text( stmt, 0 );///reading the 1st column of the result
}
else
{
cout << "Failed to open db\n";
}
sqlite3_finalize(stmt);
sqlite3_close(db);
cout << str << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当你执行一条语句时,你会得到一个表形式的结果。你有一些列,你知道的数量,和行,你不知道的数量。
首先,做一个
std::vector< std::vector < std:: string > > result;
Run Code Online (Sandbox Code Playgroud)
该string部分是单元格中的文本。内部向量是一行。外部向量是一列。
由于您确切知道rof 列的数量,因此您可以“添加列”。在您的情况下,您需要其中的 4 个:
for( int i = 0; i < 4; i++ )
result.push_back(std::vector< std::string >());
Run Code Online (Sandbox Code Playgroud)
现在,您的外部向量有 4 个元素,代表 4 列。
现在,在你的代码中你得到这样的数据
while( sqlite3_column_text( stmt, 0 ) )
{
for( int i = 0; i < 4; i++ )
result[i].push_back( std::string( (char *)sqlite3_column_text( stmt, i ) ) );
sqlite3_step( stmt );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12930 次 |
| 最近记录: |