【问题标题】:JDBC Update query errorJDBC 更新查询错误
【发布时间】:2018-04-12 11:42:46
【问题描述】:

我无法使用 where 子句在 JDBC 上执行更新查询。我想通过连接一些变量来执行查询。

protected void updateEmail(String Email, String Username) {
    try {

        conn = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "");

        String query = "update access set email=" + Email + " where username=" + Username;

        Statement st = conn.createStatement();
        st.executeUpdate(query);

    } catch (SQLException ex) {
        System.out.println(ex);
    } finally {
        try {
            conn.close();
        } catch (SQLException ex) {

        }
    }
}

上面写着:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'bhusal1' in 'where clause'

【问题讨论】:

  • 这毫无意义。您的查询中没有该列名。那是你作为参数传递的值吗?
  • 我确实有用户名为 bhusal1 的 coloum。
  • "update access set email="+Email+" where username=" ... 在此查询中,您将电子邮件和用户名作为列名,而不是 buhsal1。但 YCF_L 是对的。
  • @YCF_L 提供的答案是一种更好的方法。但是,您的代码的问题只是您忘记了引号...String query = "update access set email='" + Email + "' where username='" + Username + "'";
  • 我也试过了。字符串查询=“更新访问集电子邮件='”+电子邮件+“'其中用户名='”+用户名+“'”;

标签: java mysql jdbc


【解决方案1】:

字符串应该在两个引号 'name' 之间,而不是你必须使用 PreparedStatement 来避免语法错误或 SQL 注入:

String query = "update access set email=? where username=?";
PreparedStatement ps = con.prepareStatement(query);

ps.setString(1, email);
ps.setString(2, name);
ps.executeUpdate();

【讨论】:

  • 我该如何执行?
  • 你是什么意思@suryabhusal 你可以使用ps.executeUpdate();
  • 谢谢我,虽然可能有其他方法。没试过。对不起!
  • 谢谢@YCF_L。我熟悉 PHP 中的 Prepared Statement,但不了解 Java。非常感谢。
【解决方案2】:

这很可能是请求串联的问题。您使用的方法非常糟糕,可能会导致任何问题(包括安全性)。

为避免出现问题,需要提交sql查询参数时使用PrepareStatement。 这是一个应该可以解决您的问题的示例:

void updateEmail(String email,String username) {
    try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "")) {
        String query = "update access set email = ? where username = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, email);
            statement.setString(2, username);

            statement.executeUpdate();
        }

    }
    catch (SQLException e) {
        System.out.println(e);
    }
}

【讨论】:

    【解决方案3】:

    您应该将变量电子邮件和用户名放在 where 子句中的引号之间,以便能够进行更新查询

    【讨论】:

    • 欢迎来到 Stack。为了将来参考,在给出答案时最好包含一些代码并更彻底地解释答案。
    • 这使 OP 对 SQL 注入开放。不要给出不好的建议,即使它在技术上有效。
    • 好的,谢谢你们的建议,我会在下面的答案中尝试做得更好:)
    • 为什么不用这个答案做得更好,你仍然可以编辑它来改进它。
    猜你喜欢
    • 2016-01-04
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多