JAVA-检查结果集中的空值

JAVA-检查结果集中的空值,java,jdbc,null,resultset,Java,Jdbc,Null,Resultset,在使用之前,我需要检查从结果集中提取的值是否不为NULL。 我找到了这个解决方案 int value = 0; ResultSet rs = stmt.executeQuery(query); if (rs.next()) { value = rs.getInt("FIELD"); if (!rs.wasNull()) { // use NOT NULL field value } } 但是我需要直接检查字段值,不给变量赋值,因为数据类型事先不知道 为了更好地解

在使用之前,我需要检查从结果集中提取的值是否不为NULL。 我找到了这个解决方案

int value = 0;
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
   value = rs.getInt("FIELD");
   if (!rs.wasNull()) {
       // use NOT NULL field value
   }
}
但是我需要直接检查字段值,不给变量赋值,因为数据类型事先不知道

为了更好地解释目标,下面是我的代码:

Method method_one = null, methodResultSet=null;

switch(field_type){
    case "int":
       method_one = clazzAbstractClass.getDeclaredMethod("setValue_INT", short[].class,String.class,int.class);
       break;
   case "float":
       method_one = clazzAbstractClass.getDeclaredMethod("setValue_FLOAT", short[].class,String.class,float.class);
       break;
   case "double":
       method_one = clazzAbstractClass.getDeclaredMethod("setValue_DOUBLE", short[].class,String.class,double.class);
       break;
}

methodResultSet = clazzResultSet.getDeclaredMethod("get"+field_type.substring(0, 1).toUpperCase() + field_type.substring(1), String.class); // e.g. rs.getInt

// current call with NO CHECK on NULL                   
method_one.invoke(my_object, methodResultSet.invoke(rs, FIELD_NAME);
简而言之,代码创建了如下内容:

my_object.setValue_INT(rs.getInt("FIELD"))
注意:getInt使用0作为空值的默认值


我的目标是直接将字段值或NULL作为setValue\u INT函数的参数。

您可能可以尝试使用
ResultSet.getObject(INT columnIndex)
方法。根据其描述:

此方法将以Java语言返回给定列的值 对象Java对象的类型将是默认的Java对象 与列的SQL类型对应的类型,遵循 JDBC规范中指定的内置类型如果该值为 SQL NULL,则驱动程序返回Java NULL。


由于以这种方式检查NULL非常繁琐,因此我使用以下帮助器方法:

private static Integer getResultSetInteger(ResultSet resultset, String colName) throws SQLException {
    int v = resultset.getInt(colName);

    if (resultset.wasNull()) {
        return null;
    }

    return Integer.valueOf(v);
}

private static Double getResultSetDouble(ResultSet resultset, String colName) throws SQLException {
    double v = resultset.getDouble(colName);

    if (resultset.wasNull()) {
        return null;
    }

    return Double.valueOf(v);
}
然后,而不是

my_object.setValue_INT(rs.getInt("FIELD"));
你写

my_object.setValue_INT(getResultSetInteger(rs, "FIELD"));

ResultSetMetaData.getColumnType(int-column)
返回指定列类型的int值

ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
   if (!rs.wasNull()) {
       ResultSetMetaData rsmd = rs.getMetaData();
       //Below, i ----> column number of the column 'FIELD'.
       int type = rsmd.getColumnType(i);
        if (type == Types.VARCHAR || type == Types.CHAR) {
            System.out.print(rs.getString());
        } else {
            System.out.print(rs.getLong(i));
        }
   }
}

好啊以下解决方案是否正确:
if(rs.getObject(NAME)!=null)methodAbstractClass.invoke(my_对象,methodResultSet.invoke(rs,NAME);else methodAbstractClass.invoke(my_对象,null);