Java程序向MySQL存放图片

17 篇文章 0 订阅

Java程序向MySQL存放图片

环境

IDEA
JDK 11
8.0.11 MySQL Community Server
mysql-connector-java-8.0.21.jar

导入JAR包

MySQL官网下载页面
IDEA导入JAR包

实现代码

MySQL类

连接MySQL数据库,其中<host name>MySQL数据库公网IP,本地则为127.0.0.1<port>为端口号,MySQL数据库默认为3306<user name>为用户名,<password>为密码

package com.example.mysql;

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

package com.example.mysql;

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

public class MySQL {
    private final String URI = "jdbc:mysql://<host name>:<port>/<database name>/image?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private final String USER_NAME = "<user name>";
    private final String PASSOWRD = "<password>";
    private final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private Connection connection = null;
    public MySQL() {
        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URI, USER_NAME, PASSOWRD);
            System.out.println("MySQL Connect successfully!");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
	
	public Connection getConnection() {
        return connection;
    }
}

Database类

读取图片已二进制格式存入MySQL数据库,从MySQL读取二进制格式的字段,输出保存为图片

package com.example.mysql;

import java.io.*;
import java.sql.*;

public class Database {
    private Connection connection = null;
    private PreparedStatement preparedStatement = null;
    public Database() {
        MySQL mysql = new MySQL();
        // get connection
        connection = mysql.getConnection();
    }

    public void createImageTable() {
    	// create table to save image
    	// long binary largest object field
        String sql = "create table if not exists picture (image longblob);";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void insertImage(String path) {
        String sql = "insert into picture(image) values(?)";
        File imageFile = new File(path);

        try {
        	// read image, transform image into binary format
            FileInputStream fileInputStream = new FileInputStream(imageFile);
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setBlob(1, fileInputStream);

            if (preparedStatement.executeUpdate() > 0) {
                System.out.println("Insert successfully!");
            } else {
                System.out.println("Insert failed!");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void saveImage(FileOutputStream fileOutputStream, InputStream inputStream) {
        int len;
        byte buffer[] = new byte[1024];
		// transform binary format data into .jpg image format
        while (true) {
            try {
                if ((len = inputStream.read(buffer)) == -1) {
                    break;
                }
                fileOutputStream.write(buffer, 0, len);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public void getImage(String path) {
    	// get image from MySQL database
        String sql = "select * from picture";
        Blob imageFile;

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                imageFile = resultSet.getBlob("image");
                InputStream inputStream = imageFile.getBinaryStream();
                saveImage(fileOutputStream, inputStream);

                System.out.println("Get image successfully!");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Database database = new Database();
        database.createImageTable();
        String path = "./res/pictures/image.jpg";
        database.insertImage(path);
        String savePath = "./res/pictures/result.jpg";
        database.getImage(savePath);
    }
}

测试结果

Terminal

MySQL

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值