Question

when do I use sqlite3_step, and when do I use sqlite3_execute?

from the documentation it seems like sqlite3_step should be used after making a prepared statement,

but why would I want to run it more then one time, and why not use sqlite3_execute?

Was it helpful?

Solution

One of the values of using a prepared statement is that SQLite doesn't need to recompile the SQL statement for a bulk insert/update. If I have 100 inserts which use the same statement but are inserting different values, it would look something like this:

if (sqlite3_open(dbpath, &_database) == SQLITE_OK){
    char *errMsg;
    const char *sql_stmt = [query UTF8String];

     for each insert query{
        if (sqlite3_exec(_database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK){
            // Each statement is recompiled
        }
     }

   sqlite3_close(_database);
}

But when you are using prepared statements with binding, it looks more like this:

for each insert query {

    sqlite3_bind_text(stmt, 1, firstColumn, -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 2, secondColumn, -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(stmt, 3, thirdColumn, -1, SQLITE_TRANSIENT);

    sqlite3_step(stmt);

    sqlite3_clear_bindings(stmt);
    sqlite3_reset(stmt);

}
fclose (pFile);
sqlite3_finalize(stmt);
sqlite3_close(db);

Now instead of calling exec for each statement and having to compile the query each time, I do the bindings myself and then call sqlite3_step to evaluate each statement. The performance differences can be pretty significant.

To answer your question, use sqlite3_execute when you have one isolated query, and use prepared statements, bindings, and sqlite3_step when you are doing bulk queries. I think some would argue that you should use prepared statements and bindings everywhere you can, but frankly if you are never doing bulk queries and all of your queries are simple and isolated, then you should use the convenient sqlite_exec method (thats what it was made for!).

See this stackoverflow post for more information on performance for sqlite.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top