2016-03-07 41 views
1

該程序是一個商店,您可以添加項目的照片,您可以更新,搜索,刪除,添加等,我可以搜索,刪除和添加,但不能編輯我的項目。它一直說它有一個錯誤的sql語法,我不知道該怎麼做。請幫助。無法更新我的項目,圖像BLOB格式[JAVA]

private void btn_browseActionPerformed(java.awt.event.ActionEvent evt) {           
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); 
    FileNameExtensionFilter filter = new FileNameExtensionFilter("*.IMAGE", "jpg", "gif", "png"); 
    fileChooser.addChoosableFileFilter(filter); 
    result = fileChooser.showSaveDialog(null); 
    if (result == JFileChooser.APPROVE_OPTION) { 
     File selectedFile = fileChooser.getSelectedFile(); 
     String path = selectedFile.getAbsolutePath(); 
     label_photo.setIcon(ResizeImage(path)); 
     s = path; 
     tf = "true"; 
    } else if (result == JFileChooser.CANCEL_OPTION) { 
     System.out.println("No Data"); 
     tf = "false"; 
    } else { 
     tf = "false"; 
    } 
}           

在我的sql語法中有一個錯誤,它有什麼問題嗎?

public void update() { 
    try { 
     Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection 
     Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cake_ordering_system?" + "user=root&password="); 
     PreparedStatement pstmt = null; 

     pstmt = conn.prepareStatement("update cake set cake_name=?,cake_description=?,cake_price=?,cake_photo=? where cake_name='" + tf_search + "'"); 
     InputStream is = new FileInputStream(new File(s)); 

     //cake_name 
     pstmt.setString(1, tf_name.getText()); 
     //cake_description*/ 
     pstmt.setString(2, ta_dc.getText()); 
     //cake_price 
     pstmt.setString(3, tf_price.getText()); 
     //cake_photo 
     pstmt.setBinaryStream(4, is); 
     //execute the query 
     pstmt.executeUpdate(); 

     JOptionPane.showMessageDialog(null, "Successfully updated a new record!"); 
    } catch (Exception e) { 
     JOptionPane.showMessageDialog(null, e); 
    } 
} 
+0

我忘了刪除'''沒有看到它。 – user5789297

+0

我只是重新檢查我的數據庫,看看它是否得到更新,但它仍然是一樣的。沒有收到任何錯誤,但所有項目,不只是圖像不能更新。 – user5789297

回答

1

我寫了這段代碼來更新PostgreSQL數據庫中的圖像。

 private void updateImage(int id, File tempImagem) throws Exception { 
    try { 
     FileInputStream fis = new FileInputStream(tempImagem); 
     PreparedStatement pstm = super.operaConn.getConnDst().getConexao().prepareStatement("UPDATE table SET image = ? WHERE id = ?"); 

     byte[] imagemArray = new byte[(int) tempImagem.length()]; 
     DataInputStream imagemStream = new DataInputStream(new FileInputStream(tempImagem)); 
     imagemStream.readFully(imagemArray); 
     imagemStream.close(); 

     pstm.setBytes(1, imagemArray); 
     pstm.setInt(2, id); 
     pstm.executeUpdate(); 
     pstm.close(); 
     fis.close(); 
    } catch (Exception e) { 
     throw new Exception("ERRO no metodo updateImagem()", e); 
    } 
} 

工作的很好!