Java.sql.SQLException:调用getBytes()时参数无效

3
我试图使用以下代码将BLOB转换为字符串:
ResultSet rs = stmt.executeQuery(query);

Blob newValueBLOB = rs.getBlob("NEW_VALUE");
System.out.println(newValueBLOB);
String newValue = new String(newValueBLOB.getBytes(0, (int) newValueBLOB.length()));

我的数据库是Oracle,连接已经正常建立。我找到了一个类似的答案,但我的代码不起作用。


请阅读 [mcve] 并相应地完善您的问题。 - GhostCat
1个回答

7
根据Blob#getBytes的Javadoc:

byte[] getBytes(long pos, int length) throws SQLException
pos:要提取的BLOB值中第一个字节的序号; 第一个字节位于位置1

因此,您对getBytes()的调用应该将1作为起始位置传递,而不是零:
String newValue = new String(newValueBLOB.getBytes(1, (int) newValueBLOB.length()));

作为一种可能更简单的替代方案,你可以直接使用 ResultSet#getBytes 方法:
ResultSet rs = stmt.executeQuery(query);
byte[] newValue = rs.getBytes("NEW_VALUE");
String newValueStr = new String(newValue);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接