2017-03-01 37 views
2

我想刪除DB,其中列爲空,並利用PreparedStatement 這是我的代碼刪除使用SETNULL不工作

String deletesql = "delete from user where e-mail = ?"; 
PreparedStatement prestmt = conn.prepareStatement(deletesql); 
prestmt.setNull(1,Types.VARCHAR); 
prestmt.executeUpdate(); 

但這些代碼不工作

+0

爲什麼它不能正常工作,它拋出和異常還是什麼? –

+2

@YCF_L它不會工作,因爲'something = null'是未知的(或爲空)。 –

+0

mmm,謝謝@MarkRotteveel :) –

回答

2

嘗試
String deletesql = "delete from user where e-mail is null"; 

如果事情是未知(NULL)這不等於別的東西(=

0

看這裏https://stackoverflow.com/a/19836582 你必須使用「DELETE WHERE e-mail IS NULL」這樣的語句並省略「setNull」調用。可能你想把它放到一個單獨的準備好的語句中,因爲它只適用於NULL列。

2

在SQL something = null是未知的,您需要使用something is null,或在參數something is ?和使用setNull(1, Types.NULL)的情況下。

如果你想有你需要使它更復雜一點null和非空值:

(something is ? or something = ?) 

甚至(以前可能無法在所有的數據庫工作):

(? is null and something is null or something = ?) 

然後用:

if (something == null) { 
    stmt.setNull(1, Types.NULL); 
    // NOTE: check behavior of your db, some might require a non-null value here 
    stmt.setXxxx(2, null); 
} else { 
    // Setting a null-type parameter to a non-null value should mark it as not null 
    stmt.setObject(1, "not null", Types.NULL); 
    // Use appropriate setter 
    stmt.setXxxx(2, something); 
}