05.JDBC技术之操作Blob类型

Blob类型数据存取

@Test
public void insertPhoto()  {
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
        //存入数据库,当图片大于max_allowed_packet时,需在mysqlsever/my.ini文件修改max_allowed_packet的值
        conn = JDBCUtils.getConnection();
        String sql="insert into fruit(id,photo)values(?,?);";
        pstmt = conn.prepareStatement(sql);
        pstmt.setObject(1,5);
        FileInputStream is=new FileInputStream(new File("D:\\Users\\Desktop\\study\\图片\\photo.png"));
        pstmt.setObject(2,is);
        pstmt.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        JDBCUtils.closeResoure(conn,pstmt);
    }

}
@Test
public void loadPhoto(){
    //取出存入本地
    Connection conn = null;
    PreparedStatement pstmt = null;
    InputStream is=null;
    FileOutputStream fos=null;
    ResultSet rs=null;
    try {
        conn = JDBCUtils.getConnection();
        String sql="select * from fruit where id=?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setObject(1,5);
        rs =pstmt.executeQuery();
        while (rs.next()){
            int id=rs.getInt(1);
            //关键转换
            Blob photo=rs.getBlob(2);
            is= photo.getBinaryStream();
            fos =new FileOutputStream("D:\\Users\\Desktop\\study\\图片\\photo1.png");
            byte[] buffer=new byte[1024];
            int len;
            while ((len=is.read(buffer))!= -1){
                fos.write(buffer,0,len);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JDBCUtils.closeResoure(conn,pstmt,rs);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值