在DB2 Java存储过程中动态创建Blob

时间:2010-06-22 09:25:45

标签: sql stored-procedures jdbc db2 blob

我想将一些数据作为Blob从用Java编写的DB2存储过程中返回。

这是在DB2服务器上生成过程的代码:

CREATE PROCEDURE CLUB.P_CLUB_GET_BACKUP ( IN CLUBID INTEGER,
                                          IN BNR INTEGER,
                                          OUT BACKUP BLOB(50000000) )
 NO SQL
 NOT DETERMINISTIC
 LANGUAGE Java
 EXTERNAL NAME 'P_CLUB_GET_BACKUP:ch.swissasp.vvv.procedures.P_GET_BACKUP1.p_GET_BACKUP1'
 FENCED
 THREADSAFE
 PARAMETER STYLE JAVA

相应的Java代码是这样的:

/**
 * SQLJ Stored Procedure P_GET_BACKUP
 * @param clubID 
 * @param backupID 
 * @param Backup 
 */
package ch.swissasp.vvv.procedures;

import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

    public class P_GET_BACKUP1
    {
     public static void p_GET_BACKUP1(int clubID, int backupNr, java.sql.Blob[] backup)
      throws SQLException,
       Exception
     {
        // create blob and return as output parameter 'backup'
     }
    }

我现在需要的是从存储过程中生成的某些二进制数据生成Blob的某种方式(因此blob不是来自查询而是读取驻留在数据库服务器上的数据)然后返回此blob作为输出参数'backup'。问题是,我不知道如何动态创建blob,因为java.sql.Blob本身就是一个接口。我可以使用伪SQL创建一个blob:

// create a blob the complicated way...
Connection con = DriverManager.getConnection("jdbc:default:connection");
con.setReadOnly(true);
PreparedStatement stmt = con.prepareStatement("VALUES (Cast(? AS Blob))");
stmt.setBytes(1, new byte[0]);
ResultSet rs = stmt.executeQuery();
rs.next();
Blob blob = rs.getBlob(1);
rs.close();

然后像这样使用它:

OutputStream out = blob.setBinaryStream(1L); // get output stream to blob
// code to write the data to output stream
out.close(); // close blob
backup[0] = blob; // set output param

但我最好能用这样的东西替换所有SQL代码:

java.sql.Blob blob = new DB2Blob(); // dynamically allocate blob

是否存在在DB2中动态创建blob的工具?

1 个答案:

答案 0 :(得分:0)

以下是IBM建议的内容。您可以只使用Java代码进行查询,而不是使用DB2存储过程。

PreparedStatement preparedStatement = 
    connection.prepareStatement(
    "SELECT BOOKCOVER FROM BOOKCOVERS WHERE BOOKISBN=?"); 
preparedStatement.setString(1, "0738425826"); 
ResultSet resultSet = preparedStatement.executeQuery(); 
while (resultSet.next()) { 
    // materialization of the Blob 
    Blob blob = resultSet.getBlob(1); 
    InputStream inputStream = blob.getBinaryStream(); 
    File fileOutput = new 
        File("C:\\clonedredbookcover.jpg"); 
    FileOutputStream fo = new
        FileOutputStream(fileOutput); 
    int c; 
    while ((c = inputStream.read()) != -1) 
        fo.write(c); 
    fo.close(); 
    System.out.println("Blob retrieved");