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);
        }
    }

 

posted on 2022-03-30 08:06  金满仓  阅读(52)  评论(0编辑  收藏  举报

导航