当前位置:Gxlcms > 数据库问题 > JDBC插入二进制的数据

JDBC插入二进制的数据

时间:2021-07-01 10:21:17 帮助过:17人阅读

public void test4() throws Exception { //获取连接 Connection conn = JDBCUtils.getConnection(); // 获取PreparedStatement String sql = "insert into student(sname,photo)values(?,?)"; PreparedStatement ps = conn.prepareStatement(sql); // 填充占位符 ps.setString(1, "xxx"); InputStream fis = new FileInputStream("xxx.jpg"); ps.setBlob(2, fis); // 执行SQL ps.executeUpdate(); // 关闭资源 JDBCUtils.closeResource(conn,ps); }

 

 二、取出一个二进制数据,需要采用InputStream和OutputStream对象

例如将刚刚存的图片取出来:异常和工具类没给请见谅

@Test
public void test5() throws Exception {
    //获取数据库连接
    Connection conn = JDBCUtils.getConnection();
    // 获取PreparedStatement
    String sql = "select sname,photo from student where id = ?";
    PreparedStatement ps = conn.prepareStatement(sql);
    // 填充占位符
    ps.setInt(1, 1);
    // 执行SQL
    ResultSet rs = ps.executeQuery();
    //将返回的对象处理,将图片取出
    if(rs.next()){
        String sname = rs.getString(1);
        Blob blob = rs.getBlob(2);
        InputStream is = blob.getBinaryStream();
        OutputStream os = new FileOutputStream("HHH.jpg");
        byte [] buffer = new byte[1024];
        int len = 0;
        while((len = is.read(buffer)) != -1){
            os.write(buffer, 0, len);
        }
    }
    // 关闭资源
    JDBCUtils.close(conn,ps);
}    

 

JDBC插入二进制的数据

标签:throws   cep   connect   xxx   nbsp   getc   java   from   file   

人气教程排行