使用oracle数据库,我需要检查我的'users'表中的用户是否被禁止。如果用户的“禁止”栏的值为“1”,则禁止用户,如果不是,则禁止“0”。
我在这里有以下工作代码:
public boolean banUser(String username)
{//TODO check if user is banned already
try
{
pstmnt = conn.prepareStatement("UPDATE users SET banned = 1 WHERE username = ?");
pstmnt.setString(1, username);
pstmnt.execute();
logger.info("Banned User : " + username);
return true;
} catch ( SQLException e ) { e.getMessage(); }
return false;
}
我不确定如何在准备好的声明之上执行if语句。有什么想法吗?
答案 0 :(得分:2)
从以下位置更改您的更新声明:
conn.prepareStatement("UPDATE users SET banned = 1 WHERE username = ?");
为:
conn.prepareStatement("UPDATE users SET banned = 1 WHERE username = ? and banned = 0");
使用executeUpdate()
代替execute()
执行。区别在于executeUpdate
返回受更新影响的行数,因此如果用户已被禁止,则无需执行SQL语句来检索。
//...
pstmnt = conn.prepareStatement("UPDATE users SET banned = 1 WHERE username = ? and banned = 0");
pstmnt.setString(1, username);
int affectedRows = pstmnt.executeUpdate();
boolean wasUserBanned = affectedRows > 0;
//...
答案 1 :(得分:1)
使用此查询,并将结果存储在ResultSet
SELECT * FROM users WHERE username = ? AND banned = 1
这将返回所有具有特定用户名的被禁用户。
pstmnt = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND banned = 1");
pstmnt.setString(1, username);
ResultSet rs = pstmnt.executeQuery();
if(rs.next()) {
//The user is banned
} else {
//The user is not banned
}
如果您需要方法版本:
public boolean isUserBanned(String user) throws SQLException {
pstmnt = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND banned = 1");
pstmnt.setString(1, username);
ResultSet rs = pstmnt.executeQuery();
return rs.next();
}
答案 2 :(得分:1)
这是我对@ BackSlash版本的变体,假设username
具有UNIQUE约束:
pstmnt = conn.prepareStatement(
"SELECT COUNT(*) FROM users WHERE username = ? AND banned = 1");
pstmnt.setString(1, username);
ResultSet rs = pstmnt.executeQuery(); // Always returns exactly one row.
rs.next();
return rs.getBoolean(1); // Converts 0, 1 to false, true.
您可以让数据库使用
完成更多工作CREATE VIEW BANNED_USERS AS
SELECT username FROM USERS
WHERE banned = 1;
答案 3 :(得分:0)
更新后运行选择:
pstmnt = conn.prepareStatement("SELECT banned FROM users WHERE username = ?");
Resultset rs = pstmnt.execute();
pstmnt.setString(1, username);
int isBanned = 0;
while(rs.next()) {
isBanned = rs.getInt(1);
}
if(isBanned == 1) {
System.out.println("User is banned")
}
答案 4 :(得分:-1)
重用您的代码:(假设用户已存在)
public boolean isUserBanned(String username)
{//TODO check if user is banned already
try
{
pstmnt = conn.prepareStatement("select username WHERE username = ? and banned = 1");
pstmnt.setString(1, username);
Resultset rs = pstmnt.executeQuery();
//logger.info("Banned User : " + username);
return rs.next();
} catch ( SQLException e ) { e.getMessage(); }
return false;
}