簡體   English   中英

Java DAO更新查詢失敗

[英]java DAO update query failure

我正在嘗試編寫DAO方法以僅使用兩列來更新postgres表“ accounts”中的值:“ id”字符串“ balance” int

public Account setAccountBalance(String id, Integer balance) {
    Handle h = dbi.open();

    try{
        return h.createQuery("UPDATE accounts SET balance=" + balance.intValue() +
                            " WHERE id=\'" + id +"\';")
                .mapTo(Account.class)
                .first();
    } finally {
        h.close();
    }
}

但是在執行時,我看到以下異常:org.skife.jdbi.v2.exceptions.NoResultsException:查詢沒有結果集,也許您要更新? [語句:“ UPDATE帳戶SET余額= 20 WHERE id ='1';”,位於:“ UPDATE帳戶SET余額= 20 WHERE id ='1';”,重寫:“ UPDATE帳戶SET余額= 20 WHERE id ='1';” 1';“,參數:{位置:{},命名:{id:'1'},查找器:[]}]

知道問題在於查詢語法還是使用DAO?

看起來您正在使用JDBI 根據文檔,可以通過Handle.execute()執行SQL UPDATE,如下所示:

h.execute("UPDATE accounts SET balance=? WHERE id=?", balance.intValue(), id);

但是execute方法不會返回結果集,因此不能用於創建Account對象。 為此,您需要發出一個單獨的查詢,例如

return h.createQuery("SELECT id, balance FROM accounts WHERE id = :id")
            .bind("id", id)
            .mapTo(Account.class)
            .first();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM