dar*_*099 4 java mysql jdbc fileinputstream
为了完成一项任务,我必须将图像以 blob 格式存储到 MySQL 中(即使将图像路径存储在数据库中并将图像保存在 localcopy 的文件夹中会更好也更理想)。
到目前为止,我已经研究过并找不到任何可以帮助我的答案,这就是我迄今为止所做的
单击按钮后,将立即触发:
empdao.insertImage(fis);
Run Code Online (Sandbox Code Playgroud)
图像填充在另一个偶数侦听器上,如下所示:
static FileInputStream fis = null;
static String path = null;
path = filechooser.getSelectedFile().getAbsolutePath();
File image = new File(path);
fis = new FileInputStream (image);
Run Code Online (Sandbox Code Playgroud)
下面的代码负责将其添加到数据库中。
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();
}
Run Code Online (Sandbox Code Playgroud)
然而,问题是我需要它来将它转换为 blob,但我不知道如何转换,有人可以帮助我或指导我如何将所选图像作为 blob 字段存储到 MySQL 中。
目前,当它将它添加到数据库中时,我在图片列下输入了 java.io 文件。
假设您my_picures在 MySQL 中有一个表,带有id INT PRIMARY KEY,name 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)