【java/oracle】从blob字段读取数据到文件例子

表:

create table tb0504(
    id number(12),
    content blob,
    primary key(id)
);

程序:

package com.hy.lab.blob;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.*;

public class BlobReader {
    //-- 以下为连接Oracle数据库的四大参数
    private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
    private static final String USER = "luna";
    private static final String PSWD = "1234";

    public static void main(String[] args){
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL, USER, PSWD);

            String insertSql="select content from tb0504 where id=1";
            pstmt = conn.prepareStatement(insertSql);
            ResultSet rs=pstmt.executeQuery();
            while(rs.next()){
                Blob blob=rs.getBlob(1);
                InputStream is=blob.getBinaryStream();
                FileOutputStream os=new FileOutputStream("c:\\temp1\\new2.jpg");

                byte[] arr=new byte[1024];
                int n=is.read(arr);
                while(n!=-1){
                    os.write(arr,0,n);
                    n=is.read(arr);
                }
                is.close();
                os.close();

                break;
            }

            rs.close();

            System.out.println("完成一次读出");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

END

 

posted @ 2022-05-04 14:26  逆火狂飙  阅读(421)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东