将任何图像作为Blob保存到MySQL

时间:2013-03-20 07:27:42

标签: java mysql blob

我有这个代码在MySQL中保存图像,但它不起作用。

FileInputStream fis = null;
PreparedStatement ps = null;
MyDB.con.setAutoCommit(false);
File pic = new File(txtPicPath.getText().trim());
fis = new FileInputStream(pic);
ps = MyDB.con.prepareStatement("insert into `photo`(`Employee ID`, Picture) values (?, ?)");
ps.setString(1, Data.User.getText());
ps.setBinaryStream(2, fis, pic.length());
ps.executeUpdate();
MyDB.con.commit();
JOptionPane.showMessageDialog(rootPane, "Upload Successfully");
btnPicdelete.setEnabled(true);
btnBrowse.setEnabled(false);
btnUpload.setEnabled(false);
txtPicPass.setText("");    
txtPicPath.setText("");

问题是:

java.io.FileNotFoundException: image1.jpg (The system cannot find the file specified)

我上传的图片名称为image1.jpg

2 个答案:

答案 0 :(得分:0)

您需要在jTextField中指定图像的完整路径,或者您可以使用getClass().getResource()作为替代方法!

示例:

URL url = this.getClass().getResource("../Image/pyPic.jpg");  
                InputStream is = url.openStream();  

答案 1 :(得分:0)

我的文件名必须是:

txtPicPath.setText(file.getAbsoluteFile().toString())