[英]HOW to write select query in java using jdbc where to need to check if COLUMN IS NULL?
嘗試使用 jdbc oracle 驅動程序在 java 中的選擇查詢中編寫 ind 為 null 的條件。
代碼 :
完成所有數據庫連接
info.add("CN");
info.add("NULL");
嘗試:
ResultSet rs1 = st.executeQuery("select COUNT(*) from TABLENAME where A='" + info.get(i) + " and ind is'" +info.get(i+1) + " '");
注意:使用oracle驅動JDBC API。
從數組列表中獲取空值。但它不會從數據庫中獲取正確的值。
代碼:
完成所有數據庫連接
info.add("CN");
info.add("NULL");
ResultSet rs1 = st.executeQuery("select COUNT(*) from TABLENAME where A='" + info.get(i) + " and ind IS '" +info.get(i+1) + " '");
我希望輸出像計數(行數):
BAsic sql 查詢(如果在 DB 中使用):
select COUNT(*)
from TABLENAME
where A= 'a'
and ind IS null;
首先處理 NULL 與處理值不同:
ind IS NULL
ind = '...'
這使得使用准備好的語句變得困難。 但是應該使用 PreparedStatement ,不僅用於安全(針對SQL 注入),還用於轉義單引號等。 並且是類型安全的,因為它使用類型和轉換。
Oracle SQL 有一個缺陷,它不能區分 NULL 和 '',因此您可以使用 '' 代替。 Oracle 獨立將是:
// Typed fields:
String a = ...;
int n = ...;
String ind = null;
String sql = ind == null
? "select COUNT(*) from TABLENAME where A=? and n=? and ind is null"
: "select COUNT(*) from TABLENAME where A=? and n=? ind = ?";
try (PreparedStatement stmt = new PreparedStatement(sql)) {
stmt.setString(1, a);
stmt.setInt(2, n);
if (ind != null) {
stmt.setString(3, ind);
}
try (ResultSet rs = stmt.executeQuery()) {
long count = rs.next() ? rs.getLong(1) : 0L;
return count;
}
}
Try-with-resources 關閉語句和結果集,中間也有拋出異常或返回。
對於一般對象列表,可以使用一個 for 循環構建 SQL 模板,使用第二個來設置 PreparedStatement 的字段。
這部分:
" and ind is'" +info.get(i+1) + " '");
生成以下 SQL:
and ind is 'NULL ';
這是錯誤的,因為它會拋出錯誤:
ORA-00908: 缺少 NULL 關鍵字
您需要將其更改為:
" and ind is " +info.get(i+1));
但是對於非空值,它將不再起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.