引言

准备工作

在开始之前,请确保以下准备工作已经完成:

  1. 安装并配置MySQL数据库。
  2. 创建一个Java项目,并添加MySQL驱动库。
  3. 配置数据库连接信息。

创建数据库表

CREATE TABLE image_data (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    image BLOB
);

Java代码示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ImageStorageExample {
    private static final String URL = "jdbc:mysql://localhost:3306/your_database";
    private static final String USER = "your_username";
    private static final String PASSWORD = "your_password";

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        FileInputStream fis = null;

        try {
            // 加载MySQL驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 建立数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            // 创建SQL语句
            String sql = "INSERT INTO image_data (name, image) VALUES (?, ?)";
            pstmt = conn.prepareStatement(sql);

            // 设置图片文件路径
            String imagePath = "path/to/your/image.jpg";
            File imageFile = new File(imagePath);

            // 获取图片文件输入流
            fis = new FileInputStream(imageFile);
            // 设置参数
            pstmt.setString(1, imageFile.getName());
            pstmt.setBlob(2, fis);

            // 执行SQL语句
            pstmt.executeUpdate();
            System.out.println("图片存储成功!");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (fis != null) {
                    fis.close();
                }
                if (pstmt != null) {
                    pstmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

总结