2016-01-23 42 views
0

我嘗試將照片插入數據庫,但我的數據庫只顯示空值。 這是我的代碼的一部分,點擊按鈕從我的文件中選擇照片,照片就會顯示出來。在此先感謝幫助插入照片時,爲什麼我會在dataBase中獲得空值?

btnFrontPhoto.addActionListener(new ActionListener(){ 
    String s; 
    @Override 
public void actionPerformed(ActionEvent e){ 
     Shopping post = new Shopping(); 
     if(ShoppingDA.createPost(post)){ 
    JFileChooser fileChooser = new JFileChooser(); 
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); 
    FileNameExtensionFilter filter = new FileNameExtensionFilter("*.IMAGE", "jpg","gif","png"); 
    fileChooser.addChoosableFileFilter(filter); 
    int result = fileChooser.showSaveDialog(null); 
    if(result == JFileChooser.APPROVE_OPTION){ 
     File selectedFile = fileChooser.getSelectedFile(); 
     String path = selectedFile.getAbsolutePath(); 
     lblFrontPhoto.setIcon(ResizeImage(path)); 
     s = path; 
      } 
    else if(result == JFileChooser.CANCEL_OPTION){ 
     System.out.println("No Data"); 
    } 
     } 

} 
    public ImageIcon ResizeImage(String imgPath){ 
     ImageIcon MyImage = new ImageIcon(imgPath); 
     Image img = MyImage.getImage(); 
     Image newImage = img.getScaledInstance(lblFrontPhoto.getWidth(), lblFrontPhoto.getHeight(),Image.SCALE_SMOOTH); 
     ImageIcon image = new ImageIcon(newImage); 
     return image; 
    } 

}); 

}} 

這是插入照片到我的數據庫的代碼。我不確定哪一部分是問題。

public static boolean createPost(Shopping post){ 
    boolean success = false; 
    DBController db = new DBController(); 
    String dbQuery; 
    PreparedStatement pstmt; 

    db.getConnection(); 

    dbQuery = "INSERT INTO registration2(photo) VALUES(?)"; 
    pstmt = (PreparedStatement) db.getPreparedStatement(dbQuery); 

    try { 
     pstmt.setBlob(1, post.getPhoto()); 

     if (pstmt.executeUpdate() == 1) 
       JOptionPane.showMessageDialog(null, "Data Inserted"); 
      success = true; 
     pstmt.close(); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
    db.terminate(); 
    return success; 


} 

回答

0

在你的第一部分中,你已經創建了Shopping對象'post',但沒有爲它賦值。

Shopping post = new Shopping(); 
     if(ShoppingDA.createPost(post)){...} 

而在第二部分中,您正在使用相同的對象來插入數據庫。

相關問題