2017-08-10 47 views
1

我有兩個值picIdtubId我想更新表A.但首先,我必須檢查它們是否是空的,即""。我使用兩次更新語句。我想知道是否只能使用update語句來完成此任務。Oracle11g sql可以更新語句判斷一些列是「」

String picId = ""; 
String tubId = "1"; 

if(!"".equals(picId)) { 
    String update = "update A set columnName=someValue where id=" + picId; 
    //this method for update 
    this.executeUpdate(update, new Object[]{}); 
} 
if(!"".equals(tubId)) { 
    String update = "update A set columnName=someValue where id=" + tubId; 
    this.executeUpdate(update, new Object[]{}); 
} 

非常感謝!

+0

此代碼易受SQL注入攻擊。 [使用PreparedStatements代替](https://stackoverflow.com/questions/1812891/java-escape-string-to-prevent-sql-injection)。 – Michael

+0

謝謝all.WIth你的幫助我已經知道如何處理它: –

回答

0

尊敬的瓊恩·雪諾嘗試使用in這樣的:

String update = "update A set columnName=someValue where id in (" + tubId +","+picId+")"; 
0

在這裏,你可以使用另一個變量,它給的條件基礎。

String picId=""; 
String tubId="1"; 
String sample=""; 
if(!(picID.equals(""))) 
{ 
sample=picId; 
} 
else if(!(tubId.equals(""))) 
{ 
sample=tubId; 
} 
String update = "update A set columnName=someValue where id=" + sample; 

     this.executeUpdate(update, new Object[]{}); 
+0

但如果他們都不是「」或他們都是「」? –

0

我希望你知道在SQL查詢中使用串聯是SQL注入的方式。

但是關於你的問題,你可以在WHERE子句中使用IN條件。只准備數據:

List<String> listId = new ArrayList<>(); 
if (!"".equals(picId)) { 
    listId.add(picId); 
} 
if(!"".equals(tubId)) { 
    listId.add(tubId); 
} 
String ids = listId.stream().map(_s -> String.format("'%s'", _s)).collect(Collectors.joining(",", "(", ")")); 
String update = "update A set columnName=someValue where id IN " + ids; 
this.executeUpdate(update, new Object[]{}); 
+0

爲了避免SQL注入,我改進了這個語句。並且在您的幫助下,我知道如何在SQL中使用IN關鍵字 –

+0

我很高興,它很有用。我會使用準備好的語句來執行查詢。沒有人知道SQL注入是如何執行的。 – Syroezhkin