学无先后,达者为师

网站首页 编程语言 正文

JDBC BLOB文件存取

作者:__渡己 更新时间: 2022-07-19 编程语言
  • 写 区别
    用流替换占位符
  • 写 getBinaryStream(列名) 返回InputStream
  • 代码
 public static void main(String[] args)  {
        String sql_1 ="update test set img = ? where id = ?";
        String sql_2 ="select img from test where id = ?";
        InputStream binaryStream = null;
        try (FileOutputStream fos = new FileOutputStream("animate1.jpg");
             FileInputStream fis = new FileInputStream("C:\\Users\\123\\Desktop\\可爱.jpg");
             Connection connection = JDBCUtil.getConnection();
             PreparedStatement ps = Objects.requireNonNull(connection).prepareStatement(sql_2);
        ) {
//            读入图片
//                ps.setObject(1,fis);
//                ps.setObject(2,1);
//                ps.execute();


//            读出图片
            ps.setObject(1,1);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                binaryStream =  rs.getBinaryStream("img");
                int len;
                byte[] buffer  = new byte[1024];
                while ((len = binaryStream.read(buffer))!=-1) {
                    fos.write(buffer, 0, len);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(binaryStream!=null)
                    binaryStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

补充

  • 默认BLOB最大65k 用 MEDIUMBLOB类型最大16M
  • max_allowed_packet = 16M 修改系统变量,不然最大就是最大只能1M
  • new FileOutputStream(“animate1.jpg”)构造方法封装了创建File的匿名类

原文链接:https://blog.csdn.net/qq_51682771/article/details/125859730

栏目分类
最近更新