Java SQL 访问行数据

标签 java sql jdbc

我写了一个 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") 但它不起作用。

示例邮件尚未注册:

example mail not registered yet

示例邮件已注册:

enter image description here

我的目标是检查 mailc 是否 > 0。

最佳答案

你必须像这样将 ASCount(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/

相关文章:

java - 使用 Google People API (Java) 检索有关联系人的信息

Java 运行 .jar 时出错,但 Eclipse 中没有任何内容

sql - 在 Profiler 中隐藏 SQL

sql - Oracle SQL 查询 - 使用 MAX() 函数时加入

sql - 如何在 pyspark 的 postgres jdbc 驱动程序中使用 nextval()?

java - 从对象创建对象输出流

java - REGEX 在 Java 中将每行编码的 xml 中的前导空格和制表符替换为 html 代码

java - 如何序列化对象的多个帧而不获取当前的反序列化?

SQL查询进行聚合

java - 为什么我的 JDBC 更新不起作用?