user1578897
user1578897

Reputation: 179

C++ Sqlite select statement and store as vector

I would like to select * from abe_account like this

sqlite> select * from abe_account;
admin|Peter John|admin_account|password

But I wanna do that in C++ and return each element e.g

admin as vector x[0]
Peter John as vector x[1]
admin_account as vector x[2]
password as vector x[4]

and then use it outside when I close sqlite3_close(db)

such as cout << x[0] << endl;

How do i do it, i tried to cout << str << endl;

but it print nothing.

the following code below is what I tried on my own:

#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;

}

Upvotes: 5

Views: 15519

Answers (1)

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

When you execute a statement, you get a result as a table. You have some columns, the amount of which you do know, and rows, the amount of which you do not know.

First, make a

std::vector< std::vector < std:: string > > result;

The string part is the text in a cell. The inner vector is a row. The outer vector is a column.

Since you know exactly the numbe rof columns, you can "add the columns". In your case, you need 4 of them:

for( int i = 0; i < 4; i++ )
    result.push_back(std::vector< std::string >());

Now, your outer vector has 4 elements that represent 4 columns.

Now, in your code you get the data like this

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 );
}

Upvotes: 8

Related Questions