【发布时间】:2021-01-11 18:01:10
【问题描述】:
我正在尝试使用 JDBC 更新 MySql 数据库中的记录。 方法如下:
public void updateGareCorse(CorrePer c) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBConnectionPool.getConnection();
String sql = "update corre_per set gare_corse = ?\n"
+ " where codice_pilota = ? and anno = ?";
ps = con.prepareStatement(sql);
ps.setString(1, c.getGare_corse());
ps.setString(2, c.getCodice());
ps.setInt(3, c.getAnno());
System.out.println("QUERY:\nUPDATE corre_per SET gare_corse = " + c.getGare_corse()+" WHERE anno = "+ c.getAnno() +" AND codice_pilota = " + c.getCodice()+")");
int result = ps.executeUpdate(sql);
if (result > 0) {
System.out.println("Update OK");
} else {
System.out.println("Update NOT OK");
}
con.commit();
} catch (SQLException s) {
System.err.println(s.getMessage());
Utility.printSQLException(s);
} finally {
try {
if (rs != null)
rs.close();
if (ps != null)
ps.close();
DBConnectionPool.releaseConnection(con);
} catch (SQLException s) {
System.err.println(s.getMessage());
Utility.printSQLException(s);
}
}
}
CorrePer 是一个 Java 类,它代表我的 CorrePer 表,并具有代表我的 CorrePer 属性及其 getter 和 setter 方法的变量。 现在,当我执行这个方法时,Eclipse 给出了这个错误:
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 '? where codice_pilota = ? and anno = ?' at line 1
为什么这个方法不起作用?非常感谢任何帮助。
更新:我尝试一次只传递一个参数,其他参数不是参数,但已经写在查询中,如下所示:
String sql = "update corre_per set gare_corse = \"1-\"\n"
+ " where codice_pilota = \"TSU\" and anno = ?";
ps = con.prepareStatement(sql);
//ps.setString(1, c.getGare_corse());
//ps.setString(1, c.getCodice());
ps.setInt(1, c.getAnno());
现在它只在“?”上给出错误最后:
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 2
看来参数关联有问题,但我无法弄清楚。
【问题讨论】:
-
你试过去掉“\n”吗?
-
@JeanWillianS.J.是的,我还尝试在查询中传递值,例如: update corre_per set gare_corse = \"1-\"" + " where codice_pilota = \"TSU\" and anno = ' + c.getAnno() + ' " and它没有用。
-
你真的需要这个 ps.executeUpdate(sql) 吗?你不能只使用 ps.executeUpdate() 吗?我的意思是,你已经使用了 ps = con.prepareStatement(sql);将 SQL 转换为准备好的语句,因此您只需在其中运行 SQL。
-
@JeanWillianS.J.是的,它有效,感谢您的帮助。您和 rkosegi 同时发布了相同的解决方案。