为什么此PreparedStaement引发mysql错误? [重复]

问题描述 投票:0回答:1

我正在通过jdbc连接在mysql数据库中进行插入,该连接可以完美连接,如果在执行PreparedStatement时,Tomcat会抛出一个SQL错误,提示以下内容:

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

问题是,当我通过一条语句进行查询时,它可以毫无问题地执行查询,这使我怀疑该错误实际上在PreparedSatement中。我在这里留下代码。

@Override
public void save(Planet planet) throws SQLException {
    String namePlanet = planet.getName();
    float massPlanet = planet.getMass();
    boolean habitablePlanet = planet.isHabitable();
    sql = "INSERT INTO planeta (nom,massa,habitable) VALUES (?,?,?)";
    PreparedStatement preparedStatement = conn.prepareStatement(sql);
    preparedStatement.setString(1, namePlanet);
    preparedStatement.setFloat(2, massPlanet);
    preparedStatement.setBoolean(3, habitablePlanet);
    preparedStatement.executeUpdate(sql);
}

我还将使代码保留PreparedStatement,因此您可以看到它确实有效。

@Override
public void save(Planet planet) throws SQLException {
    String namePlanet = planet.getName();
    float massPlanet = planet.getMass();
    boolean habitablePlanet = planet.isHabitable();
    sql = "insert into planeta(nom,massa,habitable) value('" + namePlanet + "'," + massPlanet + "," + habitablePlanet + ")";
    stmt.executeUpdate(sql);

}

请耐心等待我,我是学生,在此先感谢。

java mysql jdbc prepared-statement
1个回答
2
投票

就像@Jens在评论中告诉我,我必须不带参数地调用executeUpdate()

再次感谢@Jens !!

那是正确的代码:

@Override
public void save(Planet planet) throws SQLException {
    String namePlanet = planet.getName();
    float massPlanet = planet.getMass();
    boolean habitablePlanet = planet.isHabitable();
    sql = "INSERT INTO planeta (nom,massa,habitable) VALUES (?,?,?)";
    PreparedStatement preparedStatement = conn.prepareStatement(sql);
    preparedStatement.setString(1, namePlanet);
    preparedStatement.setFloat(2, massPlanet);
    preparedStatement.setBoolean(3, habitablePlanet);
    preparedStatement.executeUpdate(); // <--- Here was the error!!

}

© www.soinside.com 2019 - 2024. All rights reserved.