2012-12-08 108 views
0

我正在运行一个编译的更新查询。但是当我测试结果时,似乎没有变化。一切看起来都不错,但显然有些事情是错误的。任何人都可以看到我缺少的东西。对于SQLite来说很新,所以如果它很简单,我们很抱歉。谢谢!SQLite更新查询不起作用

public static Boolean updateHealth (int unitVal, int oldValue, int newValue) { 
    String unit = Integer.toString(unitVal); 
    String oldVal = Integer.toString(oldValue); 
    String newVal = Integer.toString(newValue); 

    System.err.printf("old val: %s, new val: %s\n", oldVal, newVal); 
    SQLiteDatabase db = myDBOpenHelper.getWritableDatabase(); 
    String where = UNIT_COLUMN + " = " + unit + " AND " + HEALTH_COLUMN + " = " + oldVal; 

    Cursor cursor = db.query(UNITS_TABLE, new String[] {UNIT_COLUMN}, where, null, null, null, null); 

    if (cursor != null) { 
     /* the record doesn't exist, cancel the operation */ 
     return false; 
    } 

    ContentValues updatedValues = new ContentValues(); 
    updatedValues.put(HEALTH_COLUMN, newVal); 

    /* SQL query clauses */ 
    String whereArgs[] = null; 

    db.update(UNITS_TABLE, updatedValues, where, whereArgs); 

    return true; 
} 
+0

当你运行这段代码时会发生什么?你期望发生什么?你能举一个具体的例子吗? –

+0

'如果(指针!= NULL)'应该永远适用。该'Cursor'可能在某些情况下,空'cursor.getCount()== 0' – zapl

回答

1

当没有检索到行时,游标不为空。所以,你必须通过if(!cursor.moveToNext()) {

更换线if (cursor != null) {顺便说一句,你不需要更新前查询数据库。您可以执行更新,查看有多少行受到影响,如果受影响的行数大于0,则返回true,否则返回false。受影响的行数由方法update返回。

+0

就是这样。谢谢。我很好奇我将如何检查在更新查询期间有多少行受到影响。我可以让这个代码更简单一些。再次感谢! – Alex