简体   繁体   English

JDBC更新查询错误

[英]JDBC Update query error

I can't execute the update query on JDBC with where clause. 我无法使用where子句在JDBC上执行更新查询。 I want to execute the query by concatenating some variables. 我想通过串联一些变量来执行查询。

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) {

        }
    }
}

It says: 它说:

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

String should be between two quotes 'name' instead of your way you have to use PreparedStatement instead to avoid syntax error or SQL Injection : 字符串应该在两个引号'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();

This is most likely a problem with concatenation of the request. 这很可能与请求串联有关。 The approach you use is extremely bad and can cause any problems (including security). 您使用的方法极其糟糕,并且可能导致任何问题(包括安全性)。

To avoid problems, use PrepareStatement when you need to submit sql query parameters. 为避免出现问题,当您需要提交sql查询参数时,请使用PrepareStatement Here's an example that should solve your problem: 这是应该解决您的问题的示例:

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);
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM