标签:throws cep connect xxx nbsp getc java from file
二进制数据,在Java中需要使用流对象去表示,通常文件采用FileInputStream和OutputStream对象
例如给数据库中存一个图片:异常和工具类没给请见谅
@Test 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); }
例如将刚刚存的图片取出来:异常和工具类没给请见谅
@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); }
标签:throws cep connect xxx nbsp getc java from file
原文地址:https://www.cnblogs.com/linglongfang/p/12692886.html