简单实现将图片存入mysql数据库中

首先,确保你已经创建了一个MySQL数据库,并且有一个表用于存储图片。这个表应该至少有两个字段:一个用于存储图片数据的BLOB类型字段,另一个用于存储图片的其他信息,比如文件名或者描述。

以下为简单的示例代码

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javafx.application.Application;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class ImageToDatabase extends Application {

    @Override
    public void start(Stage primaryStage) {
        // 数据库连接信息
        String url = "jdbc:mysql://localhost:3306/image";
        String username = "root";
        String password = "19****gh";

        // 创建文件选择器
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Select Image File");

        // 设置文件选择器的初始目录
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));

        // 添加图片过滤器
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")
        );

        // 显示文件选择器对话框
        File selectedFile = fileChooser.showOpenDialog(primaryStage);

        if (selectedFile != null) {
            try (Connection conn = DriverManager.getConnection(url, username, password)) {
                // 读取选定的图片文件
                FileInputStream fis = new FileInputStream(selectedFile);

                // 准备SQL语句
                String sql = "INSERT INTO images (image_data, image_name) VALUES (?, ?)";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setBinaryStream(1, fis, (int) selectedFile.length());
                pstmt.setString(2, selectedFile.getName());

                // 执行插入操作
                pstmt.executeUpdate();

                System.out.println("Image inserted successfully into the database.");

            } catch (SQLException | FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("No file selected.");
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

这个程序使用了JavaFX的文件选择器来让用户选择本机上的图片文件。然后将选定的图片文件读取为字节流,并将其插入到数据库中。

已成功存储的图片

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值