我在 Java - Mysql 8.0 中的准备语句有问题

I have a problem with the prepared statement in Java - Mysql 8.0

我正在处理准备好的语句查询,但是查询语法有错误(如我的控制台中所示):

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? , ? , ? )' at line 1

我不知道它有什么问题。 注意:上面的查询在 mysql 上工作(测试),我刚刚更改了 Java 中的值。

connection = DataSource.getConnection();

String insertGame = " insert into games (game_name , game_genre , game_year ) values ( ? , ? , ? ) ";
statment = connection.prepareStatement(insertGame);
statment.setString(1, game.getName());
statment.setString(2, game.getGenre());
statment.setInt(3, game.getYear());
statment.executeUpdate(insertGame);

错误是您正在使用父 class 的 Statement.executeUpdate(String) 而不是 PreparedStatement.executeUpdate()

作为语句分隔符的分号不属于提供给 JDBC 的单个语句。

    String insertGame = "insert into games (game_name, game_genre, game_year) "
        + "values (?, ?, ?)";
    try (PreparedStatement statment = connection.prepareStatement(insertGame)) {
        statment.setString(1, game.getName());
        statment.setString(2, game.getGenre());
        statment.setInt(3, game.getYear());
        statment.executeUpdate();
    }

对于其余的关闭声明,就像使用 try-with-resources 一样,很重要。 当为重复的游戏名称抛出 SQLException 时,上面的代码也会关闭 statment