MySQL查询适用于MySQL,但不适用于Java

当我通过Java运行mysql插件时,我得到了“你的SQL语法中有错误”错误,这在MySQL中工作正常.不太确定发生了什么.

桌子:

mysql> desc fauteam;
+----------+----------+------+-----+---------+----------------+
| Field    | Type     | Null | Key | Default | Extra          |
+----------+----------+------+-----+---------+----------------+
| id       | int(8)   | NO   | PRI | NULL    | auto_increment |
| officer1 | tinytext | YES  |     | NULL    |                |
| officer2 | tinytext | YES  |     | NULL    |                |
| callsign | tinytext | NO   |     | NULL    |                |
| sector   | tinytext | NO   |     | NULL    |                |
| teamDate | date     | NO   |     | NULL    |                |
| vehicle  | tinytext | NO   |     | NULL    |                |
+----------+----------+------+-----+---------+----------------+

功能:

public static int addTeam(String officer1, String officer2, String callSign, 
        String sector, String vehicle, String date, Connection conn)
        throws SQLException, ParseException {
    int id = -1;
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

    String query = "INSERT INTO fauteam (officer1,"
            + "officer2,"
            + "callsign,"
            + "sector,"
            + "teamDate,"
            + "vehicle) VALUES (?,?,?,?,?,?);";

    PreparedStatement ps = conn.prepareStatement(query);
    ps.setString(1, officer1);
    ps.setString(2, officer2);
    ps.setString(3, callSign);
    ps.setString(4, sector);
    Date d = sdf.parse(date);
    java.sql.Date jsd = new java.sql.Date(d.getTime());
    ps.setDate(5, jsd);
    ps.setString(6, vehicle);

    System.out.println(ps.toString());

    ps.executeUpdate(query);//, Statement.RETURN_GENERATED_KEYS);
    ResultSet rs = ps.getGeneratedKeys();
    while (rs.next()) {
        id = rs.getInt(1);
    }
    rs.close();
    ps.close();

    return id;
}

发送的参数:

officer1, value = c
officer2, value = d
callSign, value = 5211
vehicle, value = 1
sector, value = 1
date, value = 06/17/2015

生成的查询如下:

INSERT INTO fauteam (officer1,officer2,callsign,sector,teamDate,vehicle) VALUES ('c','d','5211','1','2015-06-17','1');

这在MySQL中运行良好.但是,当在Java中运行时,我得到:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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

我不明白是什么导致错误.有人看到我错过的任何东西吗?

最佳答案
您在调用executeUpdate(query)时“按原样”执行SQL查询.您需要调用不带参数的方法,以便使用绑定参数执行查询:

ps.executeUpdate();

请注意,executeUpdate(String query)是从标准Statement类型继承的.

转载注明原文:MySQL查询适用于MySQL,但不适用于Java - 代码日志