I’m using Netbeans and Derby database. I would like to insert to a table records with date field, so I was told to use Calendar object since it contains what I need: date (day, month and year), hour and minute.
As you can see in the code below, the table field is of type DATE.
When I try to insert the Calendar object as a String (with commas like in the code below), I get:
The syntax of the string representation of a datetime value is incorrect.
When I try to insert it without commas I get:
Syntax error: Encountered “[” at line 1, column 159
Probably something with the Calendar object. What am I missing here?
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);
You should be using
PreparedStatement#setTimestamp()to set aTIMESTAMP/DATETIMEfield (orsetDate()to set aDATEfield, but that doesn’t cover hours and minutes…).Additional bonus is that using prepared statements protects your application from SQL injection attacks.
See also:
Unrelated to the concrete problem, converting from
StringtoCalendaris pretty clumsy. Consider usingSimpleDateFormatto convert fromStringtoDate. You can then persist it asnew Timestamp(date.getTime()).