mysql blob 数据存储和读取

8 篇文章 0 订阅

存储前数据库信息




代码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值