gpt4 book ai didi

java - 如何在 Java 中将 blob 格式的图像保存到 MySQL

转载 作者:可可西里 更新时间:2023-11-01 07:21:48 24 4
gpt4 key购买 nike

出于任务的目的,我必须将图像作为 blob 格式存储到 MySQL 中(尽管将图像路径存储在数据库中并将图像保存在本地副本的文件夹中会更好和更理想)。

到目前为止我已经研究过但找不到任何可以帮助我的答案,这就是我到目前为止所做的

只要点击一个按钮,它就会被触发:

empdao.insertImage(fis);

像这样在另一个均匀的监听器上填充图像:

static FileInputStream fis = null;
static String path = null;
path = filechooser.getSelectedFile().getAbsolutePath();
File image = new File(path);
fis = new FileInputStream (image);

下面的代码负责将其添加到数据库中。

public void insertImage(FileInputStream fis) throws SQLException {



Connection c = getConnection();

String query = "INSERT INTO Picture (picture) VALUES (?)";

System.out.println(query);

PreparedStatement pstmt = c.prepareStatement(query);

pstmt.setBinaryStream(1, fis);

pstmt.executeUpdate();

c.close();
}

但是问题是我需要它来将它转换为 blob,但我不确定该怎么做,有人可以帮助我或指导我如何将所选图像作为 blob 字段存储到 MySQL 中。

目前,当它把它添加到数据库中时,我在图片列下输入了 java.io 文件。

最佳答案

假设您在 MySQL 中有一个表 my_picures,其中包含 id INT PRIMARY KEYname VARCHAR(255)、photo BLOB

然后您可以使用以下 Java 代码插入一张新图片作为 BLOB:

public class InsertPictureAsBlob {
public static void main(String[] args) throws Exception, IOException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost/databaseName", "username", "password");
String INSERT_PICTURE = "INSERT INTO my_picures(id, name, photo) VALUES (?, ?, ?)";

conn.setAutoCommit(false);
File file = new File("myPhoto.png");
try (FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement(INSERT_PICTURE)) {
ps.setString(1, "001");
ps.setString(2, "name");
ps.setBinaryStream(3, fis, (int) file.length());
ps.executeUpdate();
conn.commit();
}
}
}

关于java - 如何在 Java 中将 blob 格式的图像保存到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41369055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com