从数据库JDBC Oracle中删除现有用户

时间:2013-06-18 16:36:33

标签: java oracle jdbc

我在这里有一个工作代码,当你调用removeUser方法时,它会从数据库中删除用户。 :

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()); }
    }

但是,在删除用户之前,我需要确保用户存在,否则打印用户不存在。如何实现这一目标?

3 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:1)

pstmnt.executeUpdate()返回行数。这表示删除了多少行!!

因此,如果它的值为零,则显示消息user does not exist.

答案 2 :(得分: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");

          }