我应该始终在 android sqlite 中使用事务吗?

Should I always use transactions in android sqlite?

这是一个简单的例子:

public boolean containsId(Long userid) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("select * from " + getTableName() + " where id = " + userid, null);
    boolean rows = cursor.getCount() > 0;
    db.close();
    return rows;
}

我以为sqlite会自动启动一个事务。我的同事说我必须总是开始交易。

那么正确的模式是什么?如果我从数据库中读取数据,是否应该启动一个事务?这个table.

这个时候肯定没有别的线程会写了

No changes can be made to the database except within a transaction. Any command that changes the database (basically, any SQL command other than SELECT) will automatically start a transaction if one is not already in effect. Automatically started transactions are committed when the last query finishes.

Transactions can be started manually using the BEGIN command. Such transactions usually persist until the next COMMIT or ROLLBACK command. But a transaction will also ROLLBACK if the database is closed or if an error occurs and the ROLLBACK conflict resolution algorithm is specified.

SQLite Query Language.

是的,交易自动开始。但是,如果您在不手动启动事务的情况下执行多个查询,则会启动和完成多个事务,这会对性能产生负面影响。
此外,自动回滚机制仅在失败时回滚单个查询。