ATM when I write to the SQLite in my android app, I do it this way:
try {
for (User user: users) {
ContentValues values = new ContentValues();
databaseManager.database.beginTransaction();
values.put("user_name", user.getName());
values.put("user_email", user.getEmail());
databaseManager.database.insert("users", null, values);
}
databaseManager.database.setTransactionSuccessful();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
databaseManager.database.endTransaction();
}
But when I read from the DB, I dont use begin, setsuccessful and end:
Cursor cursor = databaseManager.database.rawQuery(SQLQueries.getUsers(), null);
if (cursor.moveToFirst()) {
if (cursor!=null) {
do {
User user = new User();
try {
user.setName(cursor.getString(cursor.getColumnIndexOrThrow("user_name")));
user.setEmail(cursor.getString(cursor.getColumnIndexOrThrow("user_email")));
} catch (Exception ex) {
ex.printStackTrace();
}
users.add(user);
} while (cursor.moveToNext());
}
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
cursor = null;
}
Should I add beginTransaction, setTransactionSuccessful and endTransaction to the read operations as well? Im pretty sure I shouldnt, but I need to be 100% on this one.
When you are not using explicit transactions, SQLite will automatically wrap a transaction around every statement.
When you write to the database, every insert
/update
/delete
call is a single statement.
If you are doing multiple such operations, you use transactions to avoid paying the transaction overhead for each of them.
A query (query
or rawQuery
) is a single statement, even if it returns multiple rows.
Therefore, using a transaction around a single query does not make any difference.
(If you have multiple queries, you could use a transaction to ensure that their results are consistent with each other even if another thread attempts to change the database between them.)
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