2013-06-18 63 views
1

我有一個工作代碼,在您調用removeUser方法時將用戶從數據庫中刪除。 :從數據庫中刪除現有用戶JDBC Oracle

public void removeUser(String username) 
    { 

     try { 
      pstmnt = conn.prepareStatement("DELETE FROM user_info WHERE username = ?"); 
      pstmnt.setString(1, username); 
      pstmnt.executeUpdate(); 

      pstmnt = conn.prepareStatement("DELETE FROM users WHERE username = ?"); 
      pstmnt.setString(1, username); 
      pstmnt.executeUpdate(); 



      //pstmnt.executeBatch(); 
      System.out.println("Removed User :" + username); 
     } catch (SQLException e) {System.out.println("Error: " + e.getMessage()); } 
    } 

但是,我需要確保用戶存在之前,我刪除他,否則打印該用戶不存在。這如何實現?

+0

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html – SJuan76

回答

4

你也可以使用的pstmnt.executeUpdate()結果,以確定是否SQL DELETE操作成功:

int rowsUpdated = pstmnt.executeUpdate(); 
if (rowsUpdated == 0) { 
    System.out.println("User does not exist"); 
} else { 
    System.out.println("User deleted"); 
} 
+0

天才!非常感謝你 – user2297666

+0

當你聲明rowsUpdated時,這是否也同時調用executeUpdate()方法? – user2297666

+0

'rowsUpdated'從方法中返回,所以是。在聲明完成之前,您將無法訪問該變量。 – Reimeus

1

pstmnt.executeUpdate()返回的行數。其中說有多少行被刪除!

因此,如果它的值爲零,然後顯示消息user does not exist.

1

調用executeUpdate將返回由調用修改的行數。做這樣的事情:

  pstmnt = conn.prepareStatement("DELETE FROM users WHERE username = ?"); 
      pstmnt.setString(1, username); 
      int rows = pstmnt.executeUpdate(); 
      if (rows == 0) { 
       //record does not exist 
       System.out.println("User does not exist"); 
      } else if (rows > 0) { 
       //there were # of rows deleted 
       System.out.println(rows + " User records deleted"); 

      }