java调用a文件_java – 使用Bytea类型在FileInputStream上使用P...

根据PostgreSQL tutorial on storing binary data,您可以使用pstm.setBinaryStream()将二进制数据传输到数据库.使用您的示例代码,这将按如下方式工作:

private void writeToDB(Connection conn, String fileName, InputStream is, String description)

throws SQLException {

String sql = "Insert into Attachment(Id,File_Name,File_Data,Description) "

+ " values (?,?,?,?)";

try (PreparedStatement pstm = conn.prepareStatement(sql)) {

Long id = this.getMaxAttachmentId(conn) + 1;

pstm.setLong(1, id);

pstm.setString(2, fileName);

pstm.setBinaryStream(3, is);

pstm.setString(4, description);

pstm.executeUpdate();

}

}

请注意,我已将PreparedStatement包装在try-with-resources statement中,这是自Java 7以来的首选方式,因为它确保即使发生异常也能正确关闭JDBC资源.

如果PostgreSQL JDBC驱动程序不接受没有显式长度参数的pstm.setBinaryStream(),则需要将用于创建输入流的File对象的length()传递给该方法.另一种方法是在方法和用途内的read the stream fully into a byte array

pstm.setBytes(3, myByteArray);

代替.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值