我对编程知之甚少。我需要将图像保存在 MySQL 数据库中。我创建了一个数据库表,并且有一列用于添加具有 longblob 数据类型的图像。我有一个按钮的代码,可以从 PC 中的文件夹中选择图像,然后将其加载到 jlable。现在我需要将此图像插入到数据库中。
这是我的代码;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc=new JFileChooser();
fc.showOpenDialog(this);
File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
jLabel1.setIcon(new ImageIcon(path));
try{
FileInputStream fin=new FileInputStream(f);
int len=(int)f.length(); Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/hss", "root", "bis123");
PreparedStatement ps=con.prepareStatement("Insert into profile values(?)");
ps.setBinaryStream(1, fin, len);
int status=ps.executeUpdate();
if(status > 0) {
jLabel2.setText("Successfully inserted in DB");
}else{
jLabel2.setText("Image not inserted!");
}
}catch(Exception e){
System.out.println(e);
}
}
Run Code Online (Sandbox Code Playgroud)