数据库Blob类型

从数据库读取数据并写入磁盘。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;

import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.sql.SQLException;


public class Test {
    public void export() {
        int i = 0;
        String sql = "select xsid,xm,dwmc,nj,zymc,bjmc,sfzjh,zp from xsxxgl_xsjbxx where zp is not null";
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection("jdbc:oracle:thin:@125.220.126.71:1521:orcl", "jwxt", "jwxt");
            st = conn.prepareStatement(sql);
            //st.setString(1, "01772");
            rs = st.executeQuery();
            while (rs.next()) {
                String dir = "D:/xspic/" + rs.getString("DWMC") + "/" + rs.getString("NJ") + "/" + rs.getString("ZYMC") + "/" + rs.getString("BJMC");
                String name = rs.getString("SFZJH") + ".jpg";
                System.out.println(dir);
                System.out.println("已导出" + (i++) + "张图片,总共15428张");
                File directory = new File(dir);
                if (!directory.exists()) {
                    directory.mkdirs(); //创建目录
                }
                Blob blob = rs.getBlob("ZP"); //Blob类型字段
                InputStream is = blob.getBinaryStream();
                OutputStream os;
                try {
                    os = new FileOutputStream(dir + File.separator + name);
                    int b = is.read();
                    while (b != -1) {
                        os.write(b);
                        b = is.read();
                    }
                    os.flush();
                    os.close();
                    is.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            rs.close();
            st.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Test().export();
    }
}

输入链接说明

猜你喜欢

转载自my.oschina.net/u/3646781/blog/1621002
今日推荐