我知道编程的知识很少。我需要将图片保存在MySQL数据库中。我已经创建了一个数据库表,并添加了一个长blob数据类型的图像列。
我有一个按钮代码,可以从电脑文件夹中选择图像,然后将其加载到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);
}
}