当前位置:   article > 正文

简单实现将图片存入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);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

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

已成功存储的图片

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/800538
推荐阅读
相关标签
  

闽ICP备14008679号