我正在使用 Netbeans 和 Derby 数据库。我想插入带有日期字段的表记录,所以我被告知使用 Calendar
对象,因为它包含我需要的内容:日期(日、月和年)、小时和分钟。
如您在下面的代码中所见,表字段的类型为 DATE
。
当我尝试将 Calendar
对象作为字符串插入时(在下面的代码中使用逗号),我得到:
The syntax of the string representation of a datetime value is incorrect.
当我尝试不带逗号插入它时,我得到:
Syntax error: Encountered "[" at line 1, column 159
可能与 Calendar 对象有关。我在这里缺少什么?
String from = fromForm.getText();
String to = toForm.getText();
String []date = dateForm.getText().split("/");
String []time = timeForm.getText().split(":");
int places = Integer.parseInt(placesForm.getText());
int closinghours=Integer.parseInt(closingHoursForm.getText());
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Integer.parseInt(date[2]),Integer.parseInt(date[1]),Integer.parseInt(date[0]),Integer.parseInt(time[0]),Integer.parseInt(time[1]));
String query="INSERT INTO APP.TRUMPS (TRUMPID,DEPART,ARRIVE,START,PLACES,PROPOSING_USER_LOGIN,CLOSING_HOURS)"+
"VALUES ('"+newTrampTrumpistClient.login+dateForm.getText()+timeForm.getText()+"','"+from+"','"+to+
"','"+calendar+"',"+places+",'"+newTrampTrumpistClient.login+"',"+closinghours+")";
String result=newTrampTrumpistClient.WritingReading("sql_insert", query);
最佳答案
你应该使用 PreparedStatement#setTimestamp()
设置 TIMESTAMP/DATETIME
字段(或 setDate()
设置 DATE
字段,但不包括小时和分钟...)。
String sql = "INSERT INTO"
+ " APP.TRUMPS (TRUMPID, DEPART, ARRIVE, START, PLACES, PROPOSING_USER_LOGIN, CLOSING_HOURS)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?)";
// ...
PreparedStatement preparedStatement = null;
// ...
try {
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, newTrampTrumpistClient.login+dateForm.getText()+timeForm.getText());
preparedStatement.setString(2, from);
preparedStatement.setString(3, to);
preparedStatement.setTimestamp(4, new Timestamp(calendar.getTimeInMillis()));
preparedStatement.setInt(5, places);
preparedStatement.setString(6, newTrampTrumpistClient.login);
preparedStatement.setInt(7, closinghours);
preparedStatement.executeUpdate();
// ...
} finally {
// ...
}
额外的好处是使用准备好的语句可以保护您的应用程序免受 SQL injection attacks 的影响.
另见:
与具体问题无关,将 String
转换为 Calendar
非常笨拙。考虑使用 SimpleDateFormat
将 String
转换为 Date
。然后您可以将其保存为 new Timestamp(date.getTime())
。
关于java - 在 JDBC 中使用日历对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12064586/