[英]MySQL query works in MySQL but not in 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
類型繼承的。
首先,調用不帶參數的executeUpdate
; 你已經在conn.prepareStatement(query)
提供了查詢。
其次,刪除;
在語句String中,jdbc中不需要它; 當您通過交互式SQL客戶端與數據庫通信時,它只是一個(可配置的)分隔符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.