如何使用jdbc在java中编写select查询,在哪里需要检查列是否为NULL?

如何使用jdbc在java中编写select查询,在哪里需要检查列是否为NULL?,java,oracle,jdbc,Java,Oracle,Jdbc,尝试使用jdbc oracle驱动程序在java中的select查询中写入ind为null的条件 代码: 完成了所有的数据库连接 info.add("CN"); info.add("NULL"); info.add("CN"); info.add("NULL"); ResultSet rs1 = st.executeQuery("select COUNT(*) from TABLENAME where A='" + info.get(i) + " and ind IS '" +info.

尝试使用jdbc oracle驱动程序在java中的select查询中写入ind为null的条件

代码:

完成了所有的数据库连接

info.add("CN");
info.add("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) + " '");
尝试:

ResultSet rs1 = st.executeQuery("select COUNT(*) from TABLENAME where A='" + info.get(i) +  " and  ind is'" +info.get(i+1) + " '");
注意:使用oracle驱动程序JDBCAPI

从数组列表中获取空值。但它无法从数据库中获取正确的值

代码:

完成了所有的数据库连接

info.add("CN");
info.add("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) + " '");
我希望输出像count(行数):

基本sql查询(如果在数据库中使用):

select COUNT(*) 
from TABLENAME 
where A= 'a'   
 and  ind IS null;
本部分:

" and  ind is'" +info.get(i+1) + " '");
生成以下SQL:

  and ind is 'NULL ';
这是错误的,因为它会抛出错误:

ORA-00908:缺少空关键字

您需要将其更改为:

" and ind is " +info.get(i+1));

但是对于非空值,它将不再起作用

第一次处理NULL与处理值不同:

ind IS NULL
ind = '...'
这使得使用事先准备好的陈述变得困难。但是应该使用PreparedStatement,不仅用于securite(针对SQL注入),而且还用于转义单引号等。并且是类型安全的,因为它使用类型和转换

Oracle SQL有一个缺陷,即它不能区分NULL和“”,因此可以改为“”。Oracle independent将:

// 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;
   }
}

尝试资源关闭语句和结果集,同时抛出异常或返回中间。


对于常规对象列表,可以使用一个循环构造SQL模板,第二个循环设置PreparedStatement的字段。

什么是InfoDataType不要将这样的值连接到SQL字符串中。学会正确使用
PreparedStatement