简体   繁体   English

SQLite UPDATE语句更新表中的所有行

[英]SQLite UPDATE statement updates all row in table

When adding a new row to my table, I check if the row already exist, if it does, I update the row else a new row is created. 将新行添加到表中时,我检查该行是否已经存在,如果存在,则更新该行,否则会创建新行。 This works fine when I have only one row in my table. 当我的表中只有一行时,这可以正常工作。 But when I add another row and perform the same operation, all the rows in the table are updated. 但是,当我添加另一行并执行相同的操作时,表中的所有行都会更新。

Am working with these test data: 正在使用以下测试数据:

Test 1 测试1

debtorName: Ann Droid
totalOwed = 200

and this is the result: 结果是:

在此处输入图片说明

When I run the app again with the same test data, I get this result (as expected) 当我使用相同的测试数据再次运行该应用程序时,我得到了这个结果(按预期) 在此处输入图片说明

Test 2 测试2

debtorName: Vera Brown
totalOwed: 700

I get the expected result, nothing changes in the first row: 我得到了预期的结果,第一行没有任何变化: 在此处输入图片说明

but when I try to update add a new record for the second row with this test data (or any other) 但是当我尝试更新时,请使用此测试数据(或其他任何数据)为第二行添加新记录

debtorName: Vera Brown
amountOwed: 200

this happens: 有时候是这样的:

在此处输入图片说明

I've been trying to figure this out for the past 24 hours with no luck. 在过去的24小时里,我一直在设法解决这个问题,但是没有运气。 This is the update code: 这是更新代码:

public boolean updateRecord(String id,  int newTotalDebt, double newTotalOwed) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    int newTotalDebts = newTotalDebt + getDebtor(id).getTotalDebts();
    double newTotalMoneyOwed = newTotalOwed + getDebtor(id).getTotalAmountOwed();


    contentValues.put(TOTAL_DEBTS, newTotalDebts);
    contentValues.put(TOTAL_OWED, newTotalMoneyOwed);

    return db.update(DEBTOR_TABLE_NAME, contentValues, id, null) > 0;
    //db.close();


}

Any help is welcome. 欢迎任何帮助。

Finally solved it by changing my update code to this: 最终通过将更新代码更改为此来解决了这个问题:

public boolean updateRecord(String id,  int newTotalDebt, double newTotalOwed) {

    String filter = DEBTOR_ID +"= '" +id +"'";
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    int newTotalDebts = newTotalDebt + getDebtor(id).getTotalDebts();
    double newTotalMoneyOwed = newTotalOwed + getDebtor(id).getTotalAmountOwed();


    contentValues.put(TOTAL_DEBTS, newTotalDebts);
    contentValues.put(TOTAL_OWED, newTotalMoneyOwed);

    return db.update(DEBTOR_TABLE_NAME, contentValues, filter, null) > 0;
    //db.close();


}

在您的DebtDatabaseHandler类函数中,“ public boolean updateRecord(String id,int newTotalDebt,double newTotalOwed)”显示此函数需要三个参数,一个是id,它将是主键,因此您必须提供要更新的行的id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM