我需要創建一個字段更新爲一個id列表。這個列表的大小是可變的。批量更新與IN(x,x,x)
什麼我不知道是,接下來的兩個可能的選項是什麼好:
選項1:批量更新:
PreparedStatement update = connection.prepareStatement(" UPDATE table set field = value where id = ?");
for (id : ids){
update.setInt(id);
update.addBatch();
}
update.executeBatch();
選項2:IN(X,X,X)
PreparedStatement list_update = connection.prepareStatement("UPDATE table set field = value where id in (" + comma_separated_ids(ids) + ")");
private String comma_separated_ids(int[] ids){
// receives [1,2,3] and returns "1,2,3"
}
我更傾向於第二,但我不喜歡where id in (" + comma_separated_ids(ids) + ")");
因爲可能的SQL注入。
那麼,有什麼選擇更好?數字1或數字2.如果數字2是這種情況,我如何避免SQL注入?
很好的答案。謝謝,Machina =)我現在沒有時間真正衡量表現,但我想我會在未來做到這一點 – 2015-03-31 06:04:36