当我通过Java运行mysql插件时,我得到了“你的SQL语法中有错误”错误,这在MySQL中工作正常。不太确定发生了什么。
表格:
<%= f.select(:role_id, Role.all.map {|r| [r.zip_code,r.id]})%>
功能:
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
在MySQL中运行良好。但是,当在Java中运行时,我得到:
INSERT INTO fauteam (officer1,officer2,callsign,sector,teamDate,vehicle) VALUES ('c','d','5211','1','2015-06-17','1');
我不明白导致错误的原因。有人看到我错过的任何东西吗?
答案 0 :(得分:9)
您正在执行SQL查询&#34; as-is&#34;致电executeUpdate(query)
时。您需要调用不带参数的方法,以便使用绑定参数执行查询:
ps.executeUpdate();
请注意executeUpdate(String query)
继承自标准Statement
类型。
答案 1 :(得分:1)
首先,在没有参数的情况下调用executeUpdate
;您已在conn.prepareStatement(query)
中提供了查询。
其次,删除语句String中的;
,jdbc中不需要它;当您通过交互式SQL客户端与数据库通信时,它只是一个(可配置的)分隔符。