gpt4 book ai didi

java - jdbc ResultSet.get 返回 null

转载 作者:行者123 更新时间:2023-11-30 10:13:11 24 4
gpt4 key购买 nike

所以我有以下问题。我有一个通过 jdbc 连接到 Redshift-DB 的 Java 应用程序。执行一个简单的 SELECT 查询会产生一个不为空的结果集(我检查过)。

现在,当我尝试从此 ResultSet 中提取数据时,该方法有时会返回 null,即使之前的 ResultSet.wasnull() 返回 false 并且数据库中的手动检查也显示有问题的记录不包含该属性的空值。

示例代码:

    private void test(){

ResultSet rs = null;
ResultSetMetaData rsmd = null;
String getTable = "SELECT * from myTable"; //
try(PreparedStatement prep = myConnection.prepareStatement(getTable
, ResultSet.TYPE_FORWARD_ONLY
)){
rs = prep.executeQuery();
rsmd = rs.getMetaData();
int columns = rsmd.getColumnCount();

while(rs.next()){ // loop over all rows
for(int col = 1; col <= columns; col++){
if(rs.wasNull())
System.out.println("NULL Value detected!");

System.out.println("Column Name: " + rsmd.getColumnName(col));
System.out.println("Column value: " + rs.getString(col));
}
}

} catch (SQLException e) {
e.printStackTrace();
}
}

这在大多数情况下都有效,除了一些记录,rs.getString(col) 只会导致空值(即使数据库中的数据类型是 CHAR 或 VARCHAR)。这不一定对所有列都发生(我已经看到有几列被正确读取和打印,直到最终出现 null,即使 wasnull() 返回 false。

到目前为止,我已经观察到 ResultSet.getString()、ResultSet.getDate() 和 ResultSet.getTimestamp() 的这种行为,但在提取任何类型的数字(getInt()...)时从未观察到。在所有这些情况下,我检查了数据库以确保 jdbc 方法与数据类型匹配。

我尝试使用不同的驱动程序版本,我尝试使用 rs.getBytes(col) 代替,但结果保持不变:我就是无法摆脱那些空值。

我还成功地进行了卸载操作,将麻烦的表卸载到 S3 并手动检查导出的 csv 文件。 UNLOAD 运行没有任何问题,CSV 对我来说看起来很好(所有值都符合预期)。

现在我当然可以通过跳过它们出现的记录来手动处理那些“不需要的 NULL”,但我宁愿避免在不了解其原因的情况下像这样掩盖这个错误。

所以我的问题是:

我的代码有没有根本性的错误?jdbc/Redshift 是否存在可能导致此问题的已知问题?有人可以向我指出一些资源或给我一些关于我还可以尝试什么的想法吗?

最佳答案

来自 ResultSet.wasNull() 的 javadoc :

Reports whether the last column read had a value of SQL NULL. Note that you must first call one of the getter methods on a column to try to read its value and then call the method wasNull to see if the value read was SQL NULL.

Returns:
   true if the last column value read was SQL NULL and false otherwise

换句话说,您应该阅读专栏后使用它。请注意,对于对象类型,调用 wasNull 是没有意义的。 ,因为对象 getter 已经返回 null .

此方法旨在在使用原始 getter(如 getInt())读取列时使用,因为它们将返回 0。对于 null值。然后您可以使用 wasNull()检查该值是否真的是 0或者实际上 null .

换句话说,将您的代码更改为:

while(rs.next()){                               // loop over all rows
for(int col = 1; col <= columns; col++){
String value = rs.getString(col);
if(value == null)
System.out.println("NULL Value detected!");

System.out.println("Column Name: " + rsmd.getColumnName(col));
System.out.println("Column value: " + value);
}
}

或者,如果你真的想使用 wasNull() (但实际上,你不应该这样做!):

while(rs.next()){                               // loop over all rows
for(int col = 1; col <= columns; col++){
String value = rs.getString(col);
if(rs.wasNull())
System.out.println("NULL Value detected!");

System.out.println("Column Name: " + rsmd.getColumnName(col));
System.out.println("Column value: " + value);
}
}

关于java - jdbc ResultSet.get<DataType> 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51478061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com