JDBC 尝试参数更新时出错

JDBC Error when trying a parametric update

我正在尝试使用 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 class 代表我的 CorrePer table 并且具有代表我的 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

看起来参数关联有问题,但我无法弄清楚。

这是你的问题

int result = ps.executeUpdate(sql);

只需使用(因为您已经设置了参数值)

int result = ps.executeUpdate();

否则实际调用将委托给 java.sql.Statement.executeUpdate(String),它按原样执行 SQL 更新(没有参数插值,因此参数化查询中的 ? 标记不会替换为提供的值)