When using sqlite in iOS, when to do finalize statement ?
Do I need to finalize the statement after every query ?
What is the difference between reset and finalize ?
If I do reset, do I need to do finalize then ?
Thanks.
The sqlite3_finalize(S) routine can be called at any point during the life cycle of prepared statement S: before statement S is ever evaluated, after one or more calls to sqlite3_reset(), or after any call to sqlite3_step() regardless of whether or not the statement has completed execution.
SQLite is available by default on iOS. In fact, if you've used Core Data before, you've already used SQLite.
The database that can be used by apps in iOS (and also used by iOS) is called SQLite, and it's a relational database.
The sqlite3_step() runs the SQL statement. SQLITE_ROW return code indicates that there is another row ready. Our SQL statement returns only one row of data, therefore, we call this function only once. sqlite3_finalize(res); The sqlite3_finalize() function destroys the prepared statement object.
You use the sqlite3_finalize()
function when you are completely finished with a statement, either because you did a one-off query like the following:
const char *sql = "SELECT COUNT(*) FROM bonds WHERE molecule=? AND structure=?";
sqlite3_stmt *bondCountingStatement;
unsigned int totalBondCount = 0;
if (sqlite3_prepare_v2(database, sql, -1, &bondCountingStatement, NULL) == SQLITE_OK)
{
sqlite3_bind_int(bondCountingStatement, 1, databaseKey);
sqlite3_bind_int(bondCountingStatement, 2, numberOfStructureBeingDisplayed);
if (sqlite3_step(bondCountingStatement) == SQLITE_ROW)
{
totalBondCount = sqlite3_column_int(bondCountingStatement, 0);
}
else
{
}
}
sqlite3_finalize(bondCountingStatement);
or if you are done with a prepared statement that you'll never need again (possibly because you're cleaning up on exiting the application).
If you've created a statement that you'll want to use over and over again (for performance reasons, because it is reasonably expensive to prepare a statement), you use sqlite3_reset()
to reset the query so that it is ready to use again. You don't want to finalize in that case until you have decided that you'll never want to reuse that statement (again, usually this is during the teardown of your application or a particular object).
An example of a query that only resets the statement at the end is as follows:
sqlite3_bind_text(insertMoleculeSQLStatement, 1, [filename UTF8String], -1, SQLITE_TRANSIENT);
int success = sqlite3_step(insertMoleculeSQLStatement);
// Because we want to reuse the statement, we reset it instead of finalizing it.
sqlite3_reset(insertMoleculeSQLStatement);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With