Android中SQLite数据库更新一行

4

我正在开发一个安卓应用程序,在其中,我需要根据某个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子句为空时运行良好,但是当where子句被设置时会抛出强制关闭的错误。我的查询语句有问题吗?


兄弟,为什么不接受别人给你的答案呢?毕竟你不需要付钱给他们... - gunar
2
老兄,放松点。我刚看到你的答案。谢谢,它很好用。 - Dave
1
我对Stack Exchange的API知识不是很了解。我所做的就是,如果答案有用,就投票支持,并接受正确的答案。即使我没有支付任何费用,我也不能接受那些行不通并误导他人的答案,对吧?如果答案最终证明是正确的,我一定会感激帮助。抱歉,朋友,如果答案是错误的,我不会接受它。 - Dave
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});

11
难道不应该是 db.update(TABLE_PROFILE_SETTINGS_FOR_WEEKLY, values,Profile_Name_for_weekly +" = ?", new String[] {profilename}) 吗? - safari

2

如果您需要更全面的帮助来理解如何更新数据库行,请参考文档,这次文档实际上很有帮助:

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);

这个页面也很有帮助: 在Android中使用SQLite数据库进行CRUD操作

在我的情况下,我编写了一个像这样的方法:
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;
}

0

尝试使用这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接