[英]Deleting an existing user from a database JDBC Oracle
我這里有一個工作代碼,可以在您調用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()); }
}
但是,在刪除用戶之前,我需要確保該用戶存在,否則請打印該用戶不存在。 如何做到這一點?
您可以改用pstmnt.executeUpdate()
的結果來確定SQL DELETE
操作是否成功:
int rowsUpdated = pstmnt.executeUpdate();
if (rowsUpdated == 0) {
System.out.println("User does not exist");
} else {
System.out.println("User deleted");
}
pstmnt.executeUpdate()
返回行數。 這說明刪除了多少行!
因此,如果它的值為零,則顯示消息user does not exist.
。
調用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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.