其他分享
首页 > 其他分享> > JDBC操作Blob

JDBC操作Blob

作者:互联网

    public void updateBlob() throws Exception {
        String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        ps.setObject(1,"曹操");
        ps.setObject(2, "yuan@qq.com");
        ps.setObject(3,"1992-09-08");
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("bino.jpg");
        ps.setBlob(4,is);

        ps.executeUpdate();

        JDBCUtils.closeResource(connection,ps);
    }
    public void queryBlob() {
        String sql = "select photo from customers where id = ?";
        Connection connection = null;
        PreparedStatement ps = null;
        InputStream is = null;
        FileOutputStream fos = null;
        ResultSet rs = null;

        try {
            connection = JDBCUtils.getConnection();
            ps = connection.prepareStatement(sql);
            ps.setObject(1,19);
            rs = ps.executeQuery();
            if(rs.next()) {
                Blob photo = rs.getBlob("photo");
                is = photo.getBinaryStream();

                fos = new FileOutputStream("nobi.jpg");
                byte[] buffer = new byte[1024];
                int len;
                while((len = is.read(buffer)) != -1) {
                    fos.write(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            JDBCUtils.closeResource(connection,ps,rs);
        }
    }

 

标签:ps,JDBC,fos,photo,rs,connection,Blob,操作,null
来源: https://www.cnblogs.com/tsai-87/p/16074783.html