Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ SQLite3 how to know if select return 0 rows

Tags:

c++

sqlite

C++ SQLite3 how to know if select return 0 rows

I have a select statement for SQLite3, how do I know that if after executing the sql statement, the result is 0 rows , no match found etc..

How can i modify my code so that if 0 rows found, it will not execute the part where it put the result into a vector.

My code below:

sqlstatement = "SELECT * from abe_account where department="+quotesql(department)+" AND name="+quotesql(name)+";";


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


    sqlite3_prepare( db, sqlstatement.c_str() , -1, &stmt2, NULL );//preparing the statement
    sqlite3_step( stmt2 );//executing the statement

    while( sqlite3_column_text( stmt2, 0 ) )
{
    for( int i = 0; i < 4; i++ )
    result[i].push_back( std::string( (char *)sqlite3_column_text( stmt2, i ) ) );
    sqlite3_step( stmt2 );
    counter ++;
}
like image 893
baoky chen Avatar asked Aug 14 '12 16:08

baoky chen


1 Answers

sqlite3_step returns SQLITE_DONE when there are no (more) rows to process:

int stat = sqlite3_step(stmt2);
if (stat == SQLITE_DONE) {
    // no rows to process
}

Remember to check for errors as well, e.g.:

if (stat != SQLITE_DONE && stat != SQLITE_ROW) {
    // there's probably a problem
}

You can find the complete list of result codes in the manual.

Lastly, you should use the "v2" interface when using SQLite3. From the manual:

The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are recommended for all new programs. The two older interfaces are retained for backwards compatibility, but their use is discouraged.

like image 69
netcoder Avatar answered Sep 30 '22 00:09

netcoder