簡體   English   中英

使用准備好的語句執行更新查詢

[英]Executing update query, with prepared statement

 int selectie = toernooienUitvoer.getSelectedRow();
        int selectiec = toernooienUitvoer.getSelectedColumn();
        String primarykey =  (String) toernooienUitvoer.getValueAt(selectie, 0).toString();
        String waarde = toernooienUitvoer.getValueAt(selectie, selectiec).toString();

        String columnaam = toernooienUitvoer.getModel().getColumnName(selectiec).toString();
        String input = JOptionPane.showInputDialog("wijzig geselecteerde data", waarde);
        toernooienUitvoer.setValueAt(input, selectie, selectiec);   


PreparedStatement stat = con.prepareStatement("UPDATE fullhouse.toernooi SET ? = ? WHERE toernooi.T_code = ?");
        stat.setString(1, columnaam);
        stat.setString(2, input);
        stat.setString(3, primarykey);

伙計們,如果我輸入值,我知道查詢是正確的。 我猜我的錯誤是在preparedstatement中的某個地方,我得到一個MySQLSyntaxErrorException:

我認為您不能使用占位符動態傳遞列名,您的查詢應該是:

"UPDATE fullhouse.toernooi SET colname = ? WHERE toernooi.T_code = ?"

如其他答案所述,占位符? 只能用於值,不能用於表和列名。 由於您沒有重用PreparedStatement因此非常簡單。

PreparedStatement stat = con.prepareStatement("UPDATE fullhouse.toernooi SET ? = ? WHERE toernooi.T_code = ?")

PreparedStatement stat = con.prepareStatement("UPDATE fullhouse.toernooi SET " + columnName + " = ? WHERE toernooi.T_code = ?")

並在setString調用中調整index參數。

當使用綁定變量時,這意味着該語句已預編譯,並且在下一次執行時,它將更快。 您試圖將列的名稱設置為綁定變量,這是不可能的。

因為您顯然需要更新幾個不同的列,才能達到某種速度,所以應該聲明幾個准備好的語句,每列一個。 將它們保存在HashMap<String, PreparedStatement>

准備好的語句的列名不能是動態的,因為根據列名的不同,查詢計划將大相徑庭(例如,有時表掃描將是最快的,有時是使用索引,有時是更深奧的)。

如果SQL不能依靠某個計划是最快的,那么它每次都需要提出一個新計划-這意味着沒有必要編寫准備好的語句,這就是為什么您不能這樣做。

暫無
暫無

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

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