如何将BLOB数组传递给存储的oracle过程?

时间:2014-02-03 11:30:55

标签: java oracle stored-procedures jdbc

我允许用户将多个文件上传到我的数据库。这些文件内容必须作为BLOB存储在我的oracle数据库中。

我如何编写oracle程序来执行此操作? (我对Oracle存储过程有一点了解)?

一旦完成,我如何使用jdbc的CallableStatement在java中使用存储过程?

请帮忙。

4 个答案:

答案 0 :(得分:1)

首先,您必须创建包含BLOB表的类型:

CREATE OR REPLACE TYPE tab_blobs AS TABLE OF BLOB;

在Java中,您必须依赖Oracle sql提供的STRUCT类型。 您将创建一个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 ?
    }
}

答案 1 :(得分:0)

详情可在此链接中找到 loading-and-unloading-files-using-oracle-database

答案 2 :(得分:0)

这是另一种帮助你的尝试。 你可以在这里找到更多来自oracle的信息: http://docs.oracle.com/cd/B28359_01/java.111/e10788/connect.htm#CHDGHFCG http://docs.oracle.com/javase/tutorial/jdbc/basics/

此外,例子取自(我必须做的时候帮助很大的网站): http://docs.oracle.com/javase/tutorial/jdbc/basics/blob.html

public void addRowToCoffeeDescriptions(
    String coffeeName, String fileName)
    throws SQLException {

    PreparedStatement pstmt = null;
    try {
        Clob myClob = this.con.createClob();
        Writer clobWriter = myClob.setCharacterStream(1);
        String str = this.readFile(fileName, clobWriter);
        System.out.println("Wrote the following: " +
            clobWriter.toString());

        if (this.settings.dbms.equals("mysql")) {
            System.out.println(
                "MySQL, setting String in Clob " +
                "object with setString method");
            myClob.setString(1, str);
        }
        System.out.println("Length of Clob: " + myClob.length());

        String sql = "INSERT INTO COFFEE_DESCRIPTIONS " +
                     "VALUES(?,?)";

        pstmt = this.con.prepareStatement(sql);
        pstmt.setString(1, coffeeName);
        pstmt.setClob(2, myClob);
        pstmt.executeUpdate();
    } catch (SQLException sqlex) {
        JDBCTutorialUtilities.printSQLException(sqlex);
    } catch (Exception ex) {
      System.out.println("Unexpected exception: " + ex.toString());
    } finally {
        if (pstmt != null)pstmt.close();
    }
}

答案 3 :(得分:0)

以下是我的代码,希望你得到答案:

  1. 来自java代码:

            try {Class.forName("oracle.jdbc.driver.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:orcl";
            Connection con = DriverManager.getConnection(url, db_user, password);
            System.out.println("Connected to database");
    
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
            Date now = new java.sql.Date(simpleDateFormat.parse("12/02/2001").getTime());
    
            String command2 = "{call USER1(?,?,?,?)}";
    
            String path;
            File[] roots = File.listRoots();
            path=roots[0].getPath()+"dfg.jpg";
            System.out.println("path: " + path);
            //shows drives in you computer
            for(int i = 0; i < roots.length ; i++){
                System.out.println("drive: " + roots[i].getPath());
    
        }
    
            CallableStatement insertStatment = con.prepareCall(command2);
    
            insertStatment.setInt(1, 18);
            insertStatment.setString(2, "ankssaait");
            insertStatment.setDate(3, now);
    
    
            File file = new File(path);
          //link to file
            FileInputStream stream = new FileInputStream(file);
    
            insertStatment.setBinaryStream(4, stream,(int)file.length());;
            System.out.println("onExecute: "+ insertStatment.executeUpdate());
    
            insertStatment.close();
    
            System.out.println("done");
    
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
  2. 我的表格是:

    创建表“ANKIT”。“O_USER” (“NAME”VARCHAR2(20 BYTE), “GENDER”CHAR(1 BYTE), “DESIGNTION”VARCHAR2(20 BYTE), “年”间隔年(2)至月, “ID”NUMBER NOT NULL ENABLE, “DOB”日期, “证明”CLOB, “ADDRESS”VARCHAR2(100 BYTE), “电话号码, “RAW1”RAW(20), “IMAGE”BLOB,  CONSTRAINT“O_USER_PK”PRIMARY KEY(“ID”));

  3. 我的程序是:

    CREATE OR REPLACE PROCEDURE USER1 (U_ID IN o_user.id%TYPE, U_NAME in o_user.name%TYPE, u_DOB in o_user.dob%TYPE, u_image in o_user.image%TYPE) AS BEGIN insert into o_user(id,name,dob,image) values(u_id,u_name,u_dob,u_image); END USER1;