Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JDBC更新查询错误_Java_Mysql_Jdbc - Fatal编程技术网

Java JDBC更新查询错误

Java JDBC更新查询错误,java,mysql,jdbc,Java,Mysql,Jdbc,我无法使用where子句在JDBC上执行update查询。我想通过连接一些变量来执行查询 protected void updateEmail(String Email, String Username) { try { conn = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", ""); String query = "update access set e

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

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'

字符串应该位于两个引号之间
'name'
,而不是您必须使用的方式,以避免语法错误或SQL注入:

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

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

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

若要避免出现问题,请在需要提交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);
    }
}

您应该将变量email和username放在where子句的引号之间,以便能够执行更新查询

这没有意义。查询中没有该列名。这是作为参数传递的值吗?我确实有用户名为bhusal1的冒号。“更新访问集email=“+email+”where username=“。。。在这个查询中,您将电子邮件和用户名作为列名,而不是buhsal1。但是YCF_L是对的,@YCF_L提供的答案是更好的方法。但是,代码的问题只是忘记了引号
String query=“更新访问集email=”“+email+”,其中username=”“+username+”ps.executeUpdate()谢谢,我想可能还有其他方法。我没试过。很抱歉谢谢@YCF_L。我熟悉PHP中的Prepared语句,但不知道Java。非常感谢。欢迎来到Stack。作为将来的参考,在给出答案时,最好包含一些代码,并对答案进行更全面的解释。这使得OP可以接受SQL注入。不要给出错误的建议,即使技术上可行。好的,谢谢你们两位的建议,伙计们,我会在下面的答案中尝试做得更好:)为什么不用这个答案做得更好,你仍然可以编辑它来改进它。