我允许用户将多个文件上传到我的数据库。这些文件内容必须作为 BLOB 存储在我的 oracle 数据库中。
我如何编写 oracle 程序来执行此操作? (我对 Oracle 存储过程略知一二) ?
一旦完成,我如何使用 jdbc 的 CallableStatement 在 java 中使用存储过程?
请帮忙。
最佳答案
首先,您必须创建将包含 BLOB 表的类型:
CREATE OR REPLACE TYPE tab_blobs AS TABLE OF BLOB;
在Java中,你不得不依赖Oracle sql提供的STRUCT类型。 您将创建一个包含要存储到数据库中的 BLOB 数组的结构。
代码如下所示:
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.driver.OracleDriver;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;
public class ArrayDemo
{
public static void passArray()
throws SQLException
{
Connection conn = new OracleDriver().defaultConnection();
byte[] fileInByteArray = "value".getBytes();
StructDescriptor itemDescriptor = StructDescriptor.createDescriptor("BLOB", conn);
Object[] itemAtributes = new Object[] {};
STRUCT itemObject1 = new STRUCT(itemDescriptor, conn, itemAtributes);
itemAtributes = new Object[] {};
STRUCT itemObject2 = new STRUCT(itemDescriptor, conn, itemAtributes);
STRUCT[] idsArray = { itemObject1, itemObject2 };
ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor("IDS_TABLE", conn);
ARRAY array_to_pass = new ARRAY(descriptor, conn, idsArray);
OraclePreparedStatement ps = (OraclePreparedStatement) conn.prepareStatement("begin getInfo(:x); end;");
ps.setARRAY(1, array_to_pass);
ps.execute();
}
}
但是为什么不通过迭代文件来简化处理,一个接一个地插入它们:
public static void insererBlob(String name, String path) {
File file = new File(path);
try{
//link to DB
Connection connection = DriverManager.getConnection("url","user","password");
//link to file
FileInputStream stream = new FileInputStream(file);
//prepare the SQL instruction
String sql = "INSERT INTO file_table VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
//blob insertion
statement.setString(1, name);
statement.setBinaryStream(2, stream, (int)file.length());
statement.executeUpdate();
}catch(Exception e){
//ERROR SQL, IO, etc .
}finally {
//close connection ?
}
}
关于java - 如何将 BLOB 数组传递给存储的 oracle 过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21526251/