首页 > 解决方案 > JDBC中将blob插入oracle的最佳方法是什么?

问题描述

我有一个 java 代码应该将字节数组插入 Oracle 数据库到 blob 列中。函数签名是:

void loadBlob(Connection connection, byte[] byteData, PreparedStatement ps) {...}

字节数组作为参数传递(无需从任何源/流中读取)。

ps 是使用以下方法创建的:

connection.prepareStatement("insert into mytable values(?)")

mytable 脚本是:create table mytable (myblob blob)

有很多方法可以加载 blob:

  1. 使用标准的 jdbc Blob 对象
Blob blob = connection.createBlob();
blob.setBytes(1, byteData);
ps.setBlob(1, blob);
ps.execute();
blob.free();
  1. 使用 oracle 的特定对象
Blob blob = BLOB.createTemporary(connection, false, BLOB.DURATION_SESSION);
blob.setBytes(1, byteData);
ps.setBlob(1, blob);
ps.execute();
blob.free();
  1. 使用oracle的数据库函数hextoraw
PreparedStatement ps2 = connection.prepareStatement("insert into mytable values (hextoraw(?))")
//convert the byte array to hexadecimal digits - the implementation is skipped to avoid de-focus from the main issue
String hexaDigits = convertByteArrayToHexaDigits(byteData);
ps2.setString(1, hexaDigits);
ps2.execute();

问题

上述方式的优点/缺点是什么?还有其他更好的方法吗?

标签: oraclejdbcblob

解决方案


您的第一个和第二个示例似乎与我相同:

blob.setBytes(1, byteData);
ps.setBlob(1, blob);
ps.execute();
blob.free();

我可能会在您的第三个示例中选择这种方法。原因是第三个示例涉及调用 Oracle 函数hextoraw。这可能会在插入期间产生额外的开销,因此性能可能不如选项 1 或 2。


推荐阅读