【发布时间】:2014-08-07 18:18:48
【问题描述】:
在 Java 中,我尝试使用 JDBC 在 Oracle 数据库表的 BLOB 列中插入文件。
我是这样进行的:
private Statement getStatement(File f, String fid, Long dex, String uid, int id)
{
FileInputStream fis = null;
PreparedStatement statement;
try
{
statement = connection.prepareStatement("INSERT INTO BLOBTABLE (FID, FDEX, SFILE, UID, ID) VALUES (?, ?, ?, ?, ?)");
statement.setString(1, fid);
statement.setLong(2, dex);
fis = new FileInputStream(file);
statement.setBinaryStream(3, fis, file.length());
statement.setString(4, uid);
statement.setInt(5, id);
}
finally
{
if (fis != null)
fis.close();
}
return statement;
}
private insertStuff()
{
File f = new File("/home/user/thisFileExists");
PreparedStatement statement = getStatement(f, "XYZ", 18L, "ABC", 78);
statement.execute();
}
当 .execute 运行时,我得到一个 Oracle 错误:
java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("ORACLEUSER"."BLOBTABLE"."SFILE")
SFILE 是 BLOB 列。所以这意味着链末端的数据库在查询中接收到 NULL。
怎么会?
如果我替换:
statement.setBinaryStream(3, fis, file.length());
与:
statement.setBinaryStream(3, new ByteArrayInputStream(("RANDOMSTRING".getBytes())));
它可以工作,所以 it 不知何故不喜欢我的文件流。
我关闭流有问题吗?这就是他们在我看到的所有样本上的做法。
【问题讨论】:
-
在
BLOB类型列的情况下插入''一个空字符串而不是null。 -
除此之外 - 不需要
if (null != stream)的“尤达条件”。只需使用if (stream != null),大多数人会发现它更具可读性。