1

I am trying to use SQLite in C.

The interface I know exists for querying,

sqlite3_exec

Allows querying data only asynchronously (as far as I found in my searches).

Is there any way to get a result to a "Select count(*) ..." from an SQLite DB synchronously without having to implement something that waits for the data, and returns it to the same function?

I practically want to implement a "howManyItems" method that returns the actual result to its caller...

Thanks.

5
  • All SQLite querying functions execute synchronously. Are you sure you are using the official C API and not some wrapper? Commented Sep 20, 2014 at 4:15
  • I am actually not sure if the run itself is synchronous or asynchronously - but the results are definitely being returned in a callback manner (I will try the suggested solution tomorrow probably) which is out of the scope of the caller, and not how I want to get the results... Commented Sep 20, 2014 at 21:43
  • 2
    Ah, sqlite3_exec takes a callback that is called with each row. Yes, the sqlite3_prepare functions are what you want. Commented Sep 20, 2014 at 21:47
  • Thanks.. by the way - is it being run synchronously? just for knowing if my guess was right or wrong.. Commented Sep 20, 2014 at 21:57
  • 1
    Yes, it runs in the same thread. Commented Sep 20, 2014 at 21:58

1 Answer 1

4

Assuming an open sqlite3 *db, use sqlite3_prepare_v2() and sqlite3_step() (ignoring error checking for brevity):

sqlite3_stmt *statement = null;

// prepare our query
sqlite3_prepare_v2(db, "select count(*) from foo;", -1, &statement, 0);

// if there were parameters to bind, we'd do that here

// retrieve the first row (only row, in this case) of the results
int result = sqlite3_step(statement);

if (result == SQLITE_ROW)
{
  // retrieve the value of the first column (0-based)
  int count = sqlite3_column_int(statement, 0);

  // do something with count
}

// free our statement
sqlite3_finalize(statement);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.