您的位置:首页 > 数据库 > MySQL

mysql blob 数据存储和读取

2018-02-08 14:03 344 查看
存储前数据库信息代码:import java.sql.Blob;import java.sql.Connection;import java.sql.PreparedStatement;import java.io.*;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;/*** blob测试* create by frank* on 2018/02/08*/public class BlobTest {private static final String JDBC_URL = "jdbc:mysql://localhost:3306/wechatapp?useSSL=false";private static final String USER = "root";private static final String PWD = "******";private static Connection connection = null;static {connection = getConn();}public static Connection getConn() {Connection connection = null;try {connection = (Connection) DriverManager.getConnection(JDBC_URL, USER, PWD);} catch (SQLException e) {e.printStackTrace();}System.out.println("connected");return connection;}public static int update() {int rst = 0;try {InputStream inputStream = new FileInputStream("E:\\demo.jpg");String sql = "update ps_blob set img = ? where id = ?";PreparedStatement preparedStatement = connection.prepareStatement(sql);preparedStatement.setBlob(1, inputStream);preparedStatement.setInt(2, 2);rst = preparedStatement.executeUpdate();} catch (Exception e) {e.printStackTrace();}return rst;}public static void get() {String sql = "select id,img from ps_blob where id = ?";InputStream inputStream = null;try {PreparedStatement preparedStatement = connection.prepareStatement(sql);preparedStatement.setInt(1, 2);ResultSet rst = preparedStatement.executeQuery();while (rst.next()) {System.out.println("id:" + rst.getInt(1));Blob blob = rst.getBlob(2);inputStream = blob.getBinaryStream();OutputStream outputStream =new FileOutputStream("E:\\demo1.jpg");int x = 0;byte[] a = new byte[1024];while ((x = inputStream.read(a)) != -1)outputStream.write(a);outputStream.close();inputStream.close();}} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {System.out.println( BlobTest.update());BlobTest.get();}}
运行完成后查看 E:\\demo.jpg1数据库数据变化只显示(BLOB)代表插入二进制流位 byte字节数为0
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql blob