SQLITE C interface Get single-value results

When I enter Sqlite

SELECT Count(*) FROM tabl;

It returns a Number.

How to use the C interface to get this number after preparing the statement?

Open the database file, prepare statements, and make steps (for example, if there are multiple lines in the result, then You must get them one by one), extract the column values, finalize the statement, and close the database.

Something like this:

sqlite3_stmt* stmt = NULL;

sqlite3* local_db = NULL;

sqlite3_open("filename.sqlite", &local_db);

int retval, idx;
char sql[2048];

sprintf(sql, "select Something from Somewhere;");

// execute statement
retval = sqlite3_prepare_v2(local_db , sql, -1, &stmt, 0);

if(retval)
{
printf("Selecting data from DB Failed (err_code=%d) ", retval);
return;
}

// iterate rows
idx = 0;

// for multiple results
while(1)
{
// fetch a row's status
retval = sqlite3_step(stmt);

if(retval == SQLITE_ROW)
{
Something =
(int)sqlite3_column_int(stmt, 0);
// or other type-sqlite3_column_text etc.
// ... fet ch other columns, if there are any
}
else if(retval == SQLITE_DONE)
{
break;
}
else
{
sqlite3_finalize(stmt);
printf("Some error encountered ");
break;
}
}

sqlite3_finalize (stmt);

sqlite3_close(local_db);

Use this code to find all API calls (open, prepare_v2, step, column, finalize).

If this is difficult, then first you should be familiar with C itself.

When I type Sqlite

 SELECT Count(*) FROM tabl;

It returns a number.

How to use the C interface to get this number after preparing the statement?

Open the database file, prepare the statement, make the steps (for example, if there are multiple rows in the result, you must get them one by one), extract the column values, and finally determine Statement, close the database.

Something like this:

sqlite3_stmt* stmt = NULL;

sqlite3* local_db = NULL;

sqlite3_open("filename.sqlite", &local_db);

int retval, idx;
char sql[2048];

sprintf(sql, "select Something from Somewhere;");

// execute statement
retval = sqlite3_prepare_v2(local_db, sql, -1, &stmt, 0);< br />
if(retval)
{
printf("Selecting data from DB Failed (err_code=%d) ", retval);
return;
}

// iterate rows
idx = 0;

// for multiple results
while(1)
{
// fetch a row's status
retval = sqlite3_step(stmt);

if(retval == SQLITE_ROW)
{
Something =
( int)sqlite3_column_int(stmt, 0);
// or other type-sqlite3_column_text etc.
// ... fetch other columns, if there are any
}
else if(retval == SQLITE_DONE)
{
break;
}
else
{
sqlite3_finalize(stmt);
printf(" Some error encountered ");
break;
}
}

sqlite3_finalize(stmt);

sqlite3_close(local_db);

Use this code to find all API calls (open, prepare_v2, step, column, finalize).

If this is difficult, then first you should be familiar with C itself.

Leave a Comment

Your email address will not be published.