[英]replace string in java prepared mysql query statement?
在我的 java 代碼中,我想使用 SELECT 語句從表中檢索 ID。 為此,我使用 prepareStatement java 功能。
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, entry1);
pst.setString(2, entry2);
pst.setString(3, entry3);
ResultSet rs = pst.executeQuery();
entry1、entry2 和 entry3 是變量。 然而,其中一些變量可以為“null”。 所以我的 sql 語句就變成了:
SELECT ID FROM some_table WHERE col1="val1" AND col2="val2" AND col3=null;
此查詢將失敗,因此我必須將查詢更改為:
SELECT ID FROM some_table WHERE col1="val1" AND col2="val2" AND col3 IS NULL;
我該怎么做呢? 這是一個小例子,我有很多表和很多列,有時可能有 null 值。 因此,替換這部分查詢將是我能看到的最簡單的選擇。 可以這樣做還是我需要先檢查所有變量。 非常感謝!
琳達
字符串連接和三元條件運算符。
String sql = "SELECT ID" +
" FROM some_table" +
" WHERE col1 " + (entry1 != null ? "= ?" : "IS NULL") +
" AND col2 " + (entry2 != null ? "= ?" : "IS NULL") +
" AND col3 " + (entry3 != null ? "= ?" : "IS NULL");
try (PreparedStatement pst = con.prepareStatement(sql)) {
int paramIdx = 0;
if (entry1 != null)
pst.setString(++paramIdx, entry1);
if (entry2 != null)
pst.setString(++paramIdx, entry2);
if (entry3 != null)
pst.setString(++paramIdx, entry3);
try (ResultSet rs = pst.executeQuery()) {
...
}
}
您還可以嘗試NULL-safe equal (IS DISTINCT FROM)
運算符<=>
SELECT ID FROM some_table WHERE col1 <=> ? AND col2 <=> ? AND col3 <=> ?;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.