Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite3_exec without callback

Is there any way by which I can get the sqlite3_exec() result without through callback? When I do search I want to get the result directly, most like a return of the function or as OUT param?

Thanks.

like image 798
Prince AP Avatar asked Feb 07 '13 03:02

Prince AP


2 Answers

I have written some code that allows us to read data from open db (db) according to sql query (zSql) without callback. Please note, that this code works but might still need some work (for example, I'm not sure if we need to free the text data or not...)

int RunSqlNoCallback(sqlite3 * db, const char * zSql)
{
    sqlite3_stmt *stmt = NULL;
    int rc = sqlite3_prepare_v2(db, zSql, -1, &stmt, NULL);
    if (rc != SQLITE_OK)
        return rc;

    int rowCount = 0;
    rc = sqlite3_step(stmt);
    while (rc != SQLITE_DONE && rc != SQLITE_OK)
    {
        rowCount++;
        int colCount = sqlite3_column_count(stmt);
        for (int colIndex = 0; colIndex < colCount; colIndex++)
        {
            int type = sqlite3_column_type(stmt, colIndex);
            const char * columnName = sqlite3_column_name(stmt, colIndex);
            if (type == SQLITE_INTEGER)
            {
                int valInt = sqlite3_column_int(stmt, colIndex);
                printf("columnName = %s, Integer val = %d", columnName, valInt);
            }
            else if (type == SQLITE_FLOAT)
            {
                double valDouble = sqlite3_column_double(stmt, colIndex);
                printf("columnName = %s,Double val = %f", columnName, valDouble);
            }
            else if (type == SQLITE_TEXT)
            {
                const unsigned char * valChar = sqlite3_column_text(stmt, colIndex);
                printf("columnName = %s,Text val = %s", columnName, valChar);
                free(valChar);
            }
            else if (type == SQLITE_BLOB)
            {
                printf("columnName = %s,BLOB", columnName);
            }
            else if (type == SQLITE_NULL)
            {
                printf("columnName = %s,NULL", columnName);
            }
        }
        printf("Line %d, rowCount = %d", rowCount, colCount);

        rc = sqlite3_step(stmt);
    }

    rc = sqlite3_finalize(stmt);

    return rc;
}
like image 100
gerbi Avatar answered Oct 11 '22 16:10

gerbi


sqlite3_exec is a convenience wrapper.

If you don't need a callback you should use underlying functions: sqlite3_prepare_v2(), sqlite3_step(), and sqlite3_finalize() directly.

  1. Compile sql query with sqlite3_prepare_v2()
  2. Run sqlite3_step() as many times as necessary to execute the query, use sqlite3_column_bytes() etc to retrieve the data
  3. Destroy prepared query with sqlite3_finalize()

But it requires more coding and careful error handling.

like image 25
dsamersoff Avatar answered Oct 11 '22 15:10

dsamersoff