JDBC学习之路-对二进制文件的操作

create table blob_text(
id integer primary key auto_increment,
big_bit blob
)charset utf8;

对二进制文件的操作与对文本文件的操作大致相同,只是将字符输入输出流改为字节输入输出流.

public class BlobText {

    public static void main(String[] args) throws SQLException, IOException {
    creat();
    read();
    }

    static public void creat() throws SQLException, IOException{
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        //建立连接
        con = JDBCUtils.getConnection();
        //创建语句
        String sql = "insert into blob_text(big_bit) values(?)";
        ps = con.prepareStatement(sql);
        //读取文件
        File file = new File("src/imag.jpg");
        //将文件转换为字节流并读取
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        ps.setBinaryStream(1,in,(int)file.length());
        //执行语句
        int i = ps.executeUpdate();
        System.out.println("i:"+i);
    }finally{
       JDBCUtils.free(rs, ps, con);

    }


    }
    static void read() throws SQLException, IOException{
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        //建立连接
        con = JDBCUtils.getConnection();
        //创建语句
        String sql = "select big_bit from blob_text";
        ps = con.prepareStatement(sql);
        rs = ps.executeQuery();
        while(rs.next()){
        //将数据库内容存储到imag_2.jpg
        File file = new File("src/imag_2.jpg");
        // 1  为当前行中指定的列
        Blob blob = rs.getBlob(1);
        //读出流获取blob的内容
        InputStream in = blob.getBinaryStream();
        /*
         * 也可以直接写成:
         * in = rs.getCharacterStream(1);
         * 1  为当前行中指定的列
         */

        //写入流
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));

        byte[] buff = new byte[1024];    

        //将blob内容写入buff字节串中然后将buff写入文件中
        for(int i =0;(i=in.read(buff))>0;){
            out.write(buff,0,i);
        }
        out.close();
        in.close();
        }

    }finally{
        JDBCUtils.free(rs, ps, con);
    }


    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值