JDBC操作Oracle BLOB对象

将文件C:\temp\cbr_order_version.dmp从本机存入Oracle数据库BLOB字段,又从数据库读出另存为C:\temp\retrieved\retrievedBLOBcbr_order_version.dmp。


//blob_content表结构

SQL> desc blob_content
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 FILE_NAME                                 NOT NULL VARCHAR2(100)
 BLOB_COLUMN                               NOT NULL BLOB

//C:\temp\cbr_order_version.dmp文件属性,

//大小为8941568/1024/1024=8.527MB
C:\TEMP>dir cbr_order*.dmp
 Volume in drive C is OS
 Volume Serial Number is 94D2-727F

 Directory of C:\TEMP

02/06/2012  06:03 PM         8,941,568 cbr_order_version.dmp
               1 File(s)      8,941,568 bytes
               0 Dir(s)  23,012,745,216 bytes free


//java代码

package com.ssgm.jyu.jdbc;
import java.io.*;
import java.sql.*;

import oracle.sql.*;
import oracle.jdbc.*;

public class JdbcBlob {
    public static void main(String[] args){
        Connection conn = null;
        Statement stmt = null;
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }
        catch(ClassNotFoundException e){
            e.printStackTrace();
        }
        
        try{
            conn = DriverManager.getConnection("jdbc:oracle:thin:@Host:1521:SID","username","passwd");
            stmt = conn.createStatement();
            conn.setAutoCommit(false);
            String sourceDir = "C:\\temp\\";
            String targetDir = "C:\\temp\\retrieved\\";
            String fileName = "cbr_order_version.dmp";
            System.out.println("Writing BLOB to blob_content...");
            writeBLOB(stmt,sourceDir+fileName);
            System.out.println("Reading BLOB from blob_content...");
            readBLOB(stmt,fileName,sourceDir,targetDir);
        }
        catch(SQLException e){
            e.printStackTrace();
        }
        finally{
            try{
                stmt.close();
                conn.close();
            }
            catch(SQLException e){
                e.printStackTrace();
            }
        }
       }
        
        public static void writeBLOB(Statement stmt, String fullName){
            ResultSet blobRS = null;
            try{
                String sqlInsert = "INSERT INTO blob_content VALUES ('"+fullName+"',EMPTY_BLOB())";
                String sqlSelect = "SELECT blob_column FROM blob_content WHERE file_name='"+fullName+"' FOR UPDATE";
                
                //step1: initialize the LOB column to set the LOB locator                
                stmt.executeUpdate(sqlInsert);
                
                //step2: retrieve the row containing the LOB locator
                blobRS = stmt.executeQuery(sqlSelect);
                blobRS.next();
                
                //step3: create a LOB obj and read the LOB locator
                BLOB myBlob = ((OracleResultSet) blobRS).getBLOB("blob_column");
                
                //step4: get the chunksize of the LOB from the LOB object
                int chunkSize = myBlob.getChunkSize();
                
                //step5: create a buffer to hold a block of data from the file
                byte[] byteBuffer = new byte[chunkSize];
                
                //step6: create a file obj to open the file
                File file = new File(fullName);
                
                //step7: create an input stream obj to read the file contents
                FileInputStream in = new FileInputStream(file);
                
                //step8: read the file contents and write it to the LOB
                long position = 1;
                int bytesRead;
                
                while((bytesRead = in.read(byteBuffer)) != -1){
                    //write the buffer contents to myBlob
                    myBlob.setBytes(position, byteBuffer);
                    position += bytesRead;
                }
                
                //step9: commit
                stmt.execute("COMMIT");
                
                //step10: close the objects used to read the file
                in.close();
                blobRS.close();
                
                System.out.println("Wrote content from "+fullName+" to BLOB\n");
            }
            catch(SQLException e){
                System.out.println("Error Code: "+e.getErrorCode());
                System.out.println("Error Message: "+e.getMessage());
                e.printStackTrace();
            }
            catch(IOException e){
                System.out.println("Error Message: "+e.getMessage());
                e.printStackTrace();
            }
        }
        

        public static void readBLOB(
                Statement stmt,
                String fileName,
                String sourceDir,
                String targetDir){
            String sqlSelect = "SELECT blob_column FROM blob_content WHERE file_name='"+
              sourceDir+fileName+"'";
            ResultSet blobRS = null;
            try{
                //step1: retrieve the row containing the BLOB locator
                blobRS = stmt.executeQuery(sqlSelect);
                blobRS.next();
                
                //step2: create a LOB obj and read the LOB locator
                BLOB myBlob = ((OracleResultSet) blobRS).getBLOB("blob_column");
                
                //step3: get the chunk size of the LOB from the LOB obj
                int chunkSize = myBlob.getChunkSize();
                
                //setp4: create a buffer to hold a chunk of data from LOB
                byte[] byteBuffer = new byte[chunkSize];
                
                //step5: create a file obj
                String saveFile = targetDir + "retrievedBLOB"+fileName;
                File file = new File(saveFile);
                
                //step6: create output stream obj to write the LOB contents
                FileOutputStream out = new FileOutputStream(file);
                
                //step7: get the long of LOB contents
                long blobLength = myBlob.length();
                
                //step8: read a chunk of data from myBlob,
                //then write the buffer contents to file
                for (long position=1; position<=blobLength; position += chunkSize){
                    int bytesRead = myBlob.getBytes(position, chunkSize, byteBuffer);
                    out.write(byteBuffer);
                }
                
                //step9: close the stream obj
                out.close();
                
                System.out.println("Read BLOB and save file"+saveFile);
            }
            catch(SQLException e){
                System.out.println("Error Code: "+e.getErrorCode());
                System.out.println("Error Message: "+e.getMessage());
                e.printStackTrace();
            }
            catch(IOException e){
                System.out.println("Error Message: "+e.getMessage());
                e.printStackTrace();
            }
        }
        
    }


//运行时屏幕输出

Writing BLOB to blob_content...
Wrote content from C:\temp\cbr_order_version.dmp to BLOB

Reading BLOB from blob_content...
Read BLOB and save fileC:\temp\retrieved\retrievedBLOBcbr_order_version.dmp


//验证

//程序运行前USERS表空间使用空间为81M

SQL> select sum(bytes)/1024/1024 MB from dba_extents where tablespace_name='USERS';
        MB
----------
        81

//程序运行后USERS表空间使用空间为89M

SQL> select sum(bytes)/1024/1024 MB from dba_extents where tablespace_name='USERS';

        MB
----------
        89

//用sql*plus检索
SQL> select * from blob_content;
SP2-0678: Column or attribute type can not be displayed by SQL*Plus
SQL> select FILE_NAME from blob_content;

FILE_NAME
--------------------------------------------------------------------------------
C:\temp\cbr_order_version.dmp


//检查读出来的文件

C:\TEMP\retrieved>dir
 Volume in drive C is OS
 Volume Serial Number is 94D2-727F

 Directory of C:\TEMP\retrieved

02/10/2012  09:03 AM    <DIR>          .
02/10/2012  09:03 AM    <DIR>          ..
02/10/2012  09:16 AM         8,945,200 retrievedBLOBcbr_order_version.dmp
               1 File(s)      8,945,200 bytes
               2 Dir(s)  22,989,176,832 bytes free

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java连接Oracle数据库并处理BLOB数据,可以采用以下步骤: 1. 导入Oracle JDBC驱动程序。您可以从Oracle官方网站上下载适用于您的Oracle版本的JDBC驱动程序。 2. 使用JDBC API连接Oracle数据库。 3. 使用SELECT语句查询包含BLOB数据的表,并指定需要查询的BLOB列。 4. 在查询结果中,获取BLOB列的引用或句柄。 5. 使用JDBC API读取BLOB数据并将其转换为所需的格式。 6. 如果需要将BLOB数据保存到本地文件系统,可以使用Java IO流将BLOB数据写入本地文件。 以下是一个使用Java读取BLOB数据的例子: ``` import java.io.FileOutputStream; import java.io.InputStream; import java.sql.*; public class ReadBlobExample { public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { // 导入Oracle JDBC驱动程序 Class.forName("oracle.jdbc.driver.OracleDriver"); // 使用JDBC API连接Oracle数据库 conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "username", "password"); // 使用SELECT语句查询包含BLOB数据的表 pstmt = conn.prepareStatement("SELECT blob_column FROM table_name WHERE id = ?"); pstmt.setInt(1, 1); // 执行查询操作 rs = pstmt.executeQuery(); // 获取查询结果中的BLOB列 if (rs.next()) { Blob blob = rs.getBlob("blob_column"); // 获取BLOB数据的输入流 InputStream in = blob.getBinaryStream(); // 创建输出流,将BLOB数据写入本地文件 FileOutputStream out = new FileOutputStream("file_name"); byte[] buffer = new byte[1024]; int len = -1; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.close(); in.close(); } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭数据库连接和相关资源 try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } ``` 此代码示例使用Java JDBC API连接Oracle数据库,读取BLOB数据并将其写入本地文件系统。在实际应用中,您需要根据具体需求进行适当的更改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值