mysql blob 数据存储和读取

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JasonHector/article/details/79288919

存储前数据库信息




代码:

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

展开阅读全文

没有更多推荐了,返回首页