我需要在输入详细信息时检查用户名的可用性。没有人在Java中使用hibernate,有人能告诉我怎么做吗?
public static boolean checkUseName (String username) {
boolean status = false;
try {
Connection con = DB.myCon();
Statement S = con.createStatement();
String query3 = "select userId from employee where userId ='"+username+"'";
ResultSet rs = S.executeQuery(query3);
status = rs.equals("");
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
答案 0 :(得分:0)
你的错误在这里:
rs.equals("")
这将始终返回false
,因为ResultSet
永远不会等于String
。您要做的是检查ResultSet
是否为空。
这并不像看起来那么简单,因为没有isEmpty()
方法,因此您需要计算所有行,例如:
String query3 = "SELECT COUNT(*) FROM employee WHERE userId ='"+username+"'";
ResultSet rs = S.executeQuery(query3);
status = (rs.getInt(0) == 0); // Note that rs can be null here
这将使用给定条件(employee
)计算表WHERE userId ='"+username+"'
中的所有行。然后你可以检查计数是否为0。
答案 1 :(得分:0)
它使用以下代码:
public static boolean checkUseName (String username) {
boolean status = false;
try {
Connection con = DB.myCon();
Statement S = con.createStatement();
String query3 = "SELECT COUNT(*) FROM employee.user WHERE userId ='" +
username + "'";
ResultSet rs = S.executeQuery(query3);
boolean next = rs.next();
int a = rs.getInt("COUNT(*)");
status = (a == 0);
} catch (Exception e) {
e.printStackTrace();
}
return status;
}