我正在用Java创建简单的工资系统。在将图像插入无法插入的数据库中之后,我可以浏览图像并正确设置标签。我没有如何将图像插入数据库。我是Java的初学者。到目前为止我尝试过的内容附在下面。
浏览图像
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
JFileChooser fc = new JFileChooser();
if(fc.showOpenDialog(fc) == JFileChooser.APPROVE_OPTION){
BufferedImage img = ImageIO.read(fc.getSelectedFile());
ImageIcon imageIcon = new ImageIcon(new
ImageIcon(img).getImage().getScaledInstance(250, 250, Image.SCALE_DEFAULT));
imagelabel.setIcon(imageIcon);
}
} catch (IOException ex) {
Logger.getLogger(emploee.class.getName()).log(Level.SEVERE, null, ex);
}
}
将数据保存到数据库
try {
String firstname = txtfirstname.getText();
String lastname = txtlastname.getText();
String Gender;
if(jRadioButton1.isSelected())
{
Gender = "Male";
}
else
{
Gender = "Female";
}
String address = txtaddress.getText();
String batch = txtbsal.getText();
FileInputStream fin = new FileInputStream(img);
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/empay","root","");
pst = con.prepareStatement("insert into records(firstname,lastname,gender,address,bsal,photo)values(?,?,?,?,?,?)");
pst.setString(1, firstname);
pst.setString(2, lastname);
pst.setString(3, Gender);
pst.setString(4, address);
pst.setString(5, batch);
pst.setBinaryStream(6,(InputStream)fin,(int)img.length());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Registation Created...........");
} catch (ClassNotFoundException ex) {
Logger.getLogger(emploee.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(emploee.class.getName()).log(Level.SEVERE, null, ex);
}
这是我用来浏览图片的代码:
JFileChooser fc = new JFileChooser();
if(fc.showOpenDialog(fc) == JFileChooser.APPROVE_OPTION){
BufferedImage img = ImageIO.read(fc.getSelectedFile());
ImageIcon imageIcon = new ImageIcon(new
ImageIcon(img).getImage().getScaledInstance(250, 250, Image.SCALE_DEFAULT));
imagelabel.setIcon(imageIcon);
获取图像并放置img对象。我将插入数据库中的这个img对象:
BufferedImage img = ImageIO.read(fc.getSelectedFile());
将图像插入数据库:
FileInputStream fin = new FileInputStream(img);
pst.setBinaryStream(6,(InputStream)fin,(int)img.length());
显示的错误找不到符号:
错误图片: