JAVA - 检查结果集中的 NULL 值

JAVA - Checking for NULL value from a result set

我需要在使用之前检查从结果集中提取的值是否不为 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 值的默认值

我的目标是直接将 FIELD VALUE 或 NULL 作为 setValue_INT 函数的参数。

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

This method will return the value of the given column as a Java object. The type of the Java object will be the default Java object type corresponding to the column's SQL type, following the mapping for built-in types specified in the JDBC specification. If the value is an SQL NULL, the driver returns a 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) returns 指定列类型的 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));
        }
   }
}