IF中的ELSE语句删除sql joption消息

时间:2014-11-14 14:19:09

标签: java oracle swing if-statement joptionpane

我尝试创建一个if语句,但如果在jtable中找到isbn book,则显示消息" book"删除"别的"书"没找到。它有可能吗?

 private void elimina_libroActionPerformed(java.awt.event.ActionEvent evt) {      
   Connection conn = Connessione.ConnecrDb();
   Statement stmt = null;
   ResultSet emps = null;       
      boolean found = false;
    try{          
      if(emps.next()) 
      found= true;
        String sql= "DELETE FROM progetto.libro WHERE isbn =?";  
        pst=(OraclePreparedStatement) conn.prepareStatement(sql);            
        pst.setString (1, txt_isbn.getText());          
        pst.execute();               

    if (!found)
       JOptionPane.showMessageDialog(null, "LIBRO ELIMINATO"); 
   else{    
            JOptionPane.showMessageDialog(null, "BOOK NOT FOUND","ERRORE",jOptionPane.WARNING_MESSAGE); 

    }

    }
    catch (Exception e)
     {
      JOptionPane.showMessageDialog(null,e);
                }    

但是不能工作,你能帮帮我吗?感谢

我用这个

更改代码
Connection conn = Connessione.ConnecrDb();
   Statement stmt = null;
   ResultSet emps = null;

    try{

        String sql= "DELETE FROM progetto.libro WHERE isbn =?"; 

        pst=(OraclePreparedStatement) (PreparedStatement) conn.prepareStatement(sql);            
          pst.setString (1, txt_isbn.getText());          
        int deleted = pst.executeUpdate();               

if (deleted == 0) {

         JOptionPane.showMessageDialog(null, "LIBRO ELIMINATO");
         Update_table(); 


          }else
               JOptionPane.showMessageDialog(null, "LIBRO NON TROVATO");  

    }

    catch (Exception e)
     {
      JOptionPane.showMessageDialog(null,e);

    }    

但如果我插入一个不正确的isbn,则该消息为:" book delete&#34 ;,如果我插入正确的isbn,则该消息为" book not found"如果我再次插入正确的isbn消息是" book delete"这本书从数据库中删除。

2 个答案:

答案 0 :(得分:1)

    pst=(PreparedStatement) conn.prepareStatement(sql);            
    pst.setString (1, txt_isbn.getText());          
    int deleted = pst.executeUpdate();               

    if (deleted == 0) {
    ...
  

int executeUpdate()抛出SQLException

     

在此PreparedStatement对象中执行SQL语句   必须是SQL数据操作语言(DML)语句,例如   INSERT,UPDATE或DELETE;或者什么都不返回的SQL语句,   例如DDL声明。

     

返回:       (1)SQL数据操作语言(DML)语句的行计数或(2)0表示不返回任何内容的SQL语句

答案 1 :(得分:1)

变量deleted被解释错误。同样,对于每个prepareStatement,当您联系SQL驱动程序时,请更好地关闭它。

无需导入Oracle类; JDBC允许独立于供应商。

最佳做法是使用try-with-resources自动关闭pst。

String sql = "DELETE FROM progetto.libro WHERE isbn = ?"; 
try (PreparedStatement pst = conn.prepareStatement(sql)) {
    pst.setString (1, txt_isbn.getText());          
    int deletionsCount = pst.executeUpdate();               
    if (deletionsCount > 0) {
        JOptionPane.showMessageDialog(null, "LIBRO ELIMINATO");
        Update_table(); 
    } else {
        JOptionPane.showMessageDialog(null, "LIBRO NON TROVATO");  
    }
}
catch (SQLException e)
{
    JOptionPane.showMessageDialog(null, e);
}