我写了一个 Java 应用程序,用户可以在其中登录/注册。这已经在工作了。 但是不知何故,当我尝试编写逻辑来检查用户是否已经存在时,我得到了一个错误的错误。
这是我的代码:
public static void checkRegister(String mail) {
try {
// create a mysql database connection
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, user, passwordDB);
// the mysql insert statement
String query = "SELECT COUNT(email) mailc, email from users where users.email = \"" + mail + "\"";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
我尝试使用 preparedStmt.getResultSet().getInt("mailc")
但它不起作用。
示例邮件尚未注册:
示例邮件已注册:
我的目标是检查 mailc 是否 > 0。
最佳答案
你必须像这样将 AS 与 Count(c) AS col
一起使用:
String query = "SELECT COUNT(email) AS mailc, email from users ....";
我建议改用 PreparedStatement 的 ?
,以避免任何 SQL 注入(inject)。所以你的查询应该是这样的:
String query = "SELECT COUNT(email) mailc, email from users where users.email =?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, mail);
要获得结果,您必须使用 ResultSet:
String query = "SELECT COUNT(email) AS mailc, email from users where users.email =?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, mail);
ResultSet result = preparedStmt.executeQuery();
while (result.next()) {
int count = result.getInt("mailc");
String email = result.getString("email");
}
关于Java SQL 访问行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43306863/