2013-06-18 1 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

대신 SQL DELETE 작업이 성공 여부를 결정하는 pstmnt.executeUpdate()의 결과를 사용할 수 있습니다

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() 반환 행 수를. 얼마나 많은 행이 지워지는지 알려줍니다 !!

따라서 값이 0이면 메시지 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"); 

      } 
관련 문제