当我向microsoft Access插入日期时,它给了我这个错误,为什么? 这是什么意思?我确信查询是正确的。 这是我的代码:
try {
final DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
Date date = new Date();
String a = "#"+sdf.format(date)+"#";
conn=DriverManager.getConnection(dbURL);
System.out.println("Connection ok.");
id = Integer.parseInt(ID.getText());
String query = "INSERT INTO Patient(ID, FName, Address, Phone, Allergies)\n" +
"VALUES ('"+id+"', '"+ name.getText()+"', '"+ address.getText()+"', '"+phone.getText()+"', '"+allergies.getText()+ "');";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.executeUpdate();
String query2 = "INSERT INTO Visit( PatientID, ArrivalTime, HeartRate, Temprature) "+
"VALUES ('"+id+"','"+a+"', '"+heart.getText()+"', '"+temp.getText()+"');";
stmt = conn.prepareStatement(query2);
stmt.executeUpdate();
conn.close();
}catch(Exception e){
System.err.println("Exception: "+e.getMessage());
}
答案 0 :(得分:0)
声明
String a = "#"+sdf.format(date)+"#";
您已经在日期字符串周围添加了#
个分隔符。然后,您的动态SQL继续将'
分隔符放在其周围,从而产生类似
INSERT INTO Visit (PatientID, ArrivalTime, ...) VALUES ('1', '#12/29/2017 06:24:23 PM#', ...);
这是无效的语法。正确的文字语法是......
INSERT INTO Visit (PatientID, ArrivalTime, ...) VALUES (1, #12/29/2017 06:24:23 PM#, ...);
...但你真的应该不使用动态SQL。您应该使用
行的参数化查询// test data
int id = 123;
java.util.Date date = new java.util.Date();
String sql = "INSERT INTO Visit (PatientID, ArrivalTime) VALUES (?,?);";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.setTimestamp(2, new java.sql.Timestamp(date.getTime()));
ps.executeUpdate();