黑猴子的家:JDBC -> mysql 图片上传和下载

1、Mysql BLOB类型

MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据
MySQL的四种BLOB类型(除了在存储的最大信息量上不同外,他们是等同的)

9193428-cd8546f7f6f07a61.png

实际使用中根据需要存入的数据大小定义不同的BLOB类型。
需要注意的是:如果存储的文件过大,数据库的性能会下降。

2、图片上传

package com.yinggu.demo4;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.junit.Test;
import com.yinggu.utils.JDBCUtils;

 * @author:黑猴子的家
 * @博客 :https://www.jianshu.com/u/37fd8e2dff4c
 * 
 * 大数据  图片在数据库的上传和下载
 * 注意点
 *   (1)图片选小的
 *   (2)编码格式是不是utf-8
 *   (3)Stream 流别忘记关闭

public class TestBlob {
    // 上传
    @Test
    public void testSave() throws Exception {
        // 1.获取连接
        Connection connection = JDBCUtils.getConnection();
        // 2.执行
        PreparedStatement statement = connection.prepareStatement(
                "update beauty set photo=? where id=?");
        InputStream inputStream = new FileInputStream(
                "C:\\Users\\heihouzi\\Desktop\\beauty\\zdy.jpg");
        statement.setBlob(1, inputStream);
        statement.setInt(2, 5);
        int update = statement.executeUpdate();
        System.out.println(update > 0 ? "success" : "failure");
        // 3.关闭
        inputStream.close();
        JDBCUtils.closeConnection(null, statement, connection);
    }
}

3、图片下载

// 下载
@Test
public void testRead() throws Exception {
    // 1.获取连接
    Connection connection = JDBCUtils.getConnection();
    // 2.访问数据库
    PreparedStatement statement = connection.prepareStatement(
        "select photo from beauty where id=?");
    statement.setInt(1, 5);
    ResultSet set = statement.executeQuery();
    if (set.next()) {
        // 方式一:getBlob
        // Blob blob = set.getBlob(1);
        // InputStream inputStream = blob.getBinaryStream();
        // 方式二:getBinaryStream
        InputStream inputStream = set.getBinaryStream(1);
        // 写入到指定的文件中——写入到src\copy.jpg
        FileOutputStream fos = new FileOutputStream("src\\copy.jpg");
        int len;
        byte[] b = new byte[1024];
        while ((len = inputStream.read(b)) != -1) {
            fos.write(b, 0, len);
        }
        fos.close();
        inputStream.close();
    }
    // 3.关闭
    JDBCUtils.closeConnection(set, statement, connection);
}

4、注意点

(1)图片选小的
(2)编码格式是不是utf-8
(3)Stream 流别忘记关闭

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值