テーブル内の整数をインクリメントする必要があります。選択と連続更新を行う代わりに、単一のクエリでこれを行いたいです。しかし、運が悪かった。
次のコードは 0 を返します。
final SQLiteStatement stmt = helper.getWritableDatabase().
compileStatement("update my_table set my_count = my_count + 1 where _id = ?");
try
{
stmt.bindLong(1, id);
return stmt.executeUpdateDelete();
}
finally
{
stmt.close();
}
そしてもちろん、記録は更新されません。
しかし、これは 1 を返します。
final ContentValues v = new ContentValues();
v.put("my_count", 1);
return helper.getWritableDatabase().
update("my_table", v, "_id=?", new String[]{String.valueOf(id)});
指定したIDのレコードが100%存在します。トランザクション内またはトランザクションなしでこれを作成しようとしました - 結果は同じです。実際の SQLiteStatement でテストしていません。おそらく Robolectric のバグです。
誰かがこの効果に関して何らかの仮定を持っていますか? または、この問題を回避する方法についての提案はありますか (を使用しない場合もありますSQLiteStatement
)。
ありがとう。
更新 1。
簡単なテストも行っています。
@RunWith(RobolectricTestRunner.class)
public class SQLiteStatementTest
{
private static class TestOpenHelper extends SQLiteOpenHelper
{
public TestOpenHelper(Context context)
{
super(context, "test", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE test(_id INTEGER PRIMARY KEY AUTOINCREMENT, count INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
@Test
public void testExecuteUpdateDeleteModifiesRow() throws Exception
{
final int initialCount = 6;
final TestOpenHelper helper = new TestOpenHelper(Robolectric.application);
final ContentValues v = new ContentValues();
v.put("count", initialCount);
final long id = helper.getWritableDatabase().insert("test", null, v);
final SQLiteStatement stmt = helper.getWritableDatabase().
compileStatement("update test set count = count + 1 where _id=?");
stmt.bindLong(1, id);
assertThat(stmt.executeUpdateDelete(), is(1));
}
}