赞
踩
首先,确保你已经创建了一个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的文件选择器来让用户选择本机上的图片文件。然后将选定的图片文件读取为字节流,并将其插入到数据库中。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。