我正在通过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);
}
请耐心等待我,我是一名学生,在此先感谢。
答案 0 :(得分: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!!
}