Java连接Mysql数据库存取图片

1、创建数据库

CREATE TABLE `img_table`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `photo` mediumblob NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

2、数据库连接

package chapter.img;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Wang
 * @date 2021/12/24 0024 16:27
 * description
 */
public class DBUtil {
    public static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";

    public static final String URL = "jdbc:mysql://localhost:3306/test??useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";

    public static final String USERNAME = "root";

    public static final String PASSWORD = "";

    static {
        try {
            Class.forName(DRIVER_CLASS_NAME);
        }
        catch (ClassNotFoundException e){
            System.out.println("注册失败!");
            e.printStackTrace();
        }
    }

    public static Connection getConn() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    // 关闭连接
    public static void closeConn(Connection connection){
        if(null != connection){
            try {
                connection.close();
            }
            catch (SQLException e){
                System.out.println("关闭数据库连接失败!");
                e.printStackTrace();
            }
        }
    }
}

3、图片流

package chapter.img;

import java.io.*;

/**
 * @author Wang
 * @date 2021/12/24 0024 16:33
 * description
 */
public class ImageUtil {

    // 读取本地图片获取输入流
    public static FileInputStream readImage(String path) throws FileNotFoundException {
        return new FileInputStream(new File(path));
    }

    // 读取表中图片获取输入流
    public static void readBin2Image(InputStream in, String targetPath){
        File file = new File(targetPath);
        String path = targetPath.substring(0, targetPath.lastIndexOf("/"));
        if(!file.exists()){
            new File(path).mkdir();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) != -1){
                fos.write(buf, 0, len);
            }
            fos.flush();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            if(null != fos){
                try {
                    fos.close();
                }
                catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

4、转码存储

package chapter.img;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Wang
 * @date 2021/12/24 0024 16:41
 * description
 */
public class ImageDemo {

    // 将图片插入数据库
    public static void readImage2DB(){
        String path = "F:\\04.JavaLearning\\QianFengEdu\\src\\chapter\\images\\1.png";
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        FileInputStream in = null;
        try {
            in = ImageUtil.readImage(path);
            connection = DBUtil.getConn();
            String sql = "INSERT INTO img_table(name, type, photo) VALUES(?, ?, ?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "curry");
            preparedStatement.setString(2,"nba");
            preparedStatement.setBinaryStream(3, in, in.available());
            int count = preparedStatement.executeUpdate();
            if(count > 0){
                System.out.println("插入成功!");
            }else{
                System.out.println("插入失败!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.closeConn(connection);
            if(null != preparedStatement){
                try{
                    preparedStatement.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }

    // 读取数据库中的图片
    public static void readDB2Image(){
        String targetPath = "C:/Users/Administrator/Desktop/svg/2.png";
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConn();
            String sql = "SELECT * FROM img_table WHERE id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 1);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                InputStream in = resultSet.getBinaryStream("photo");
                ImageUtil.readBin2Image(in, targetPath);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.closeConn(connection);
            if(resultSet != null){
                try {
                    resultSet.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if(preparedStatement != null){
                try {
                    preparedStatement.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args){
        // 插入图片
//        readImage2DB();
        // 取出图片
        readDB2Image();
    }
}

5、实现效果

插入数据库的信息
在这里插入图片描述
取到的图片
在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中,可以使用JDBC API连接数据库,并使用BLOB(二进制大对象)数据类型来存储和检索图像。以下是一个简单的示例代码,演示了如何将图像存储在数据库中: ```java // 1. 创建数据库连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password"); // 2. 准备SQL语句 String sql = "INSERT INTO mytable (image) VALUES (?)"; PreparedStatement statement = conn.prepareStatement(sql); // 3. 读取图像文件 File file = new File("myimage.png"); FileInputStream inputStream = new FileInputStream(file); // 4. 将图像文件写入BLOB字段 statement.setBinaryStream(1, inputStream, (int) file.length()); // 5. 执行SQL语句 statement.executeUpdate(); // 6. 关闭连接和流 inputStream.close(); statement.close(); conn.close(); ``` 在上面的示例中,我们使用PreparedStatement对象来执行SQL语句,并使用setBinaryStream方法将图像文件的InputStream对象写入BLOB字段。最后,我们关闭连接和流对象以释放资源。 如果要从数据库中检索图像,请使用以下代码: ```java // 1. 创建数据库连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password"); // 2. 准备SQL语句 String sql = "SELECT image FROM mytable WHERE id=?"; PreparedStatement statement = conn.prepareStatement(sql); statement.setInt(1, 1); // 3. 执行SQL语句并获取结果集 ResultSet rs = statement.executeQuery(); // 4. 从结果集中获取BLOB字段并将其保存到文件中 if (rs.next()) { InputStream inputStream = rs.getBinaryStream("image"); OutputStream outputStream = new FileOutputStream("retrievedimage.png"); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); } // 5. 关闭连接和结果集 rs.close(); statement.close(); conn.close(); ``` 在上面的示例中,我们使用ResultSet对象获取结果集,并使用getBinaryStream方法检索BLOB字段的InputStream对象。然后,我们使用OutputStream将InputStream对象中的数据写入文件中。最后,我们关闭连接和结果集对象以释放资源。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叁拾舞

你的鼓励将是我最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值