首页 文章

Sqlite数据库更新了一行android

提问于
浏览
4

我正在开发一个Android应用程序,我需要根据某个where子句更新表中的列 . 这是下面的代码,

public void updatethekeyofweeklycolumn(String profilename, String keystemp) 
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(Profile_keysofweekly, keystemp);

    db.update(TABLE_PROFILE_SETTINGS_FOR_WEEKLY, values,Profile_Name_for_weekly +" = "+profilename, null);
}

上面的代码在where子句为null时工作正常,但是它设置了一个与whereclause关闭的力 . 我的查询错了吗?

3 回答

  • 14

    您需要转义profilename . 所以你要么添加单个'字符:

    db.update(TABLE_PROFILE_SETTINGS_FOR_WEEKLY, values,Profile_Name_for_weekly +" = '"+ profilename + "'", null);
    

    或者,我会遵循的选项:

    db.update(TABLE_PROFILE_SETTINGS_FOR_WEEKLY, values,Profile_Name_for_weekly +" = ?", new String[] {profilename});
    
  • 0

    有关了解如何更新数据库行的更一般帮助,documentation这次实际上非常有用:

    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    
    // New value for one column
    ContentValues values = new ContentValues();
    values.put(FeedEntry.COLUMN_NAME_TITLE, title);
    
    // Which row to update, based on the ID
    String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
    String[] selectionArgs = { String.valueOf(rowId) };
    
    int count = db.update(
        FeedReaderDbHelper.FeedEntry.TABLE_NAME,
        values,
        selection,
        selectionArgs);
    

    这个页面也很有帮助:Working with SQLite Database (CRUD operations) in Android

    在我的情况下,我做了这样的方法:

    public long updateTime(long rowId) {
    
        // get current Unix epoc time in milliseconds
        long date = System.currentTimeMillis();
    
        SQLiteDatabase db = helper.getWritableDatabase(); // helper is MyDatabaseHelper, a subclass database control class in which this updateTime method is resides
        ContentValues contentValues = new ContentValues();
        contentValues.put(MyDatabaseHelper.DATE_TIME, date); // (column name, new row value)
        String selection = MyDatabaseHelper.ID + " LIKE ?"; // where ID column = rowId (that is, selectionArgs)
        String[] selectionArgs = { String.valueOf(rowId) };
    
        long id = db.update(MyDatabaseHelper.FAVORITE_TABLE_NAME, contentValues, selection,
                selectionArgs);
        db.close();
        return id;
    }
    
  • 1

    试试这个:

    db.update("yourtable", cvalue, "Profile_Name_for_weekly="+"'"+profilename+"'", null);
    

相关问题