JDBC操作二进制

JDBC操作二进制

  • PreparedStatement对象可以使用输入和输出流来提供参数数据。这使您可以将整个文件放入可以保存大值的数据库列,例如Text和BLOB数据类型。
  • 有以下方法可用于流式传输数据:
    • setAsciiStream():此方法用于提供大的ASCII值。
    • setCharacterStream():此方法用于提供大型UNICODE值。
    • setBinaryStream():此方法用于提供较大的二进制值。
  • setXXXStream()方法除了参数占位符之外还需要额外的参数,文件大小。
  • 代码示例:(写入文本文件和图片)
    //注册驱动
         Class.forName("com.mysql.jdbc.Driver");
         //获取连接
         Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxx","xxx","xxx");
         //创建指令对象
         PreparedStatement preparedStatement = connection.prepareStatement("insert into bigdata values(?,?,?)");
         preparedStatement.setInt(1,1);
         //使用二进制添加图片或音频文件
         preparedStatement.setBinaryStream(2,new FileInputStream("src\\12.jpg"));
         //使用字符添加文本文件
         preparedStatement.setCharacterStream(3,new FileReader("src\\resource\\db.properties"));
         //执行更新
         preparedStatement.executeUpdate();
         //释放资源
         preparedStatement.close();
         connection.close();
    
  • 代码示例:(读取文本文件和图片)
    //注册驱动
         Class.forName("com.mysql.jdbc.Driver");
         //1获取连接
         Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxx","xxx","xxx");
         //2创建命令对象
         PreparedStatement pstat = connection.prepareStatement("select * from bigdata where id=?");
         //3设置参数
         pstat.setInt(1, 2);
         //4执行
         ResultSet rs = pstat.executeQuery();
         //5处理
         if(rs.next()){
             //获取字符文件
             Reader reader = rs.getCharacterStream("content");
             //获取音频或图片文件
             InputStream is = rs.getBinaryStream("photo");
             //处理 content
             FileWriter fw=new FileWriter("src\\empcopy.xml");
             char[] buf=new char[1024];
             int len=0;
             while((len=reader.read(buf))!=-1){
                 fw.write(buf,0,len);
                 fw.flush();
             }
             fw.close();
             reader.close();
             //处理图片
             FileOutputStream fos=new FileOutputStream("src\\004.jpg");
             byte[] buf2=new byte[1024];
             int len2=0;
             while((len2=is.read(buf2))!=-1){
                 fos.write(buf2,0,len2);
                 fos.flush();
             }
             fos.close();
             is.close();
         }
         rs.close();
         pstat.close();
         connection.close();
         System.out.println("执行完毕");
    


转载请注明:Memory的博客 » 点击阅读原文

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦