Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Insert into a table datetime data

I am trying to insert into a variable in MS- SQL database the current date and the time. I use this format:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 
Calendar cal = Calendar.getInstance();  
System.out.println(dateFormat.format(cal.getTime()));

and I get this as a result 2013-01-28 09:29:37.941

My field in the database is defined datetime and as I have seen in other tables which have the same field, the date and the time is written exactly like this 2011-07-05 14:18:33.000.

I try to insert into the database with a query that I do inside a java program, but I get this error

SQL Exception: State : S0003 Message: The conversion of a varchar data type to a datetime data type of the value is out of range. Error : 242

My query is like that:

query = "INSERT INTO Companies CreatedOn"+ 
         "VALUES ('" + dateFormat.format(cal.getTime()) + "')"

but I don't understand what I am doing wrong.

like image 989
Dimitra Micha Avatar asked Jan 28 '13 08:01

Dimitra Micha


3 Answers

According to the error description, you are inserting an incorrect type into the database. See JDBC to MSSQL. You should convert Calendar to Timestamp.

Try using:

PrepareStatement statement 
    = connection.prepareStatement("INSERT INTO Companies CreatedOn VALUES(?)");
java.sql.Timestamp timestamp = new java.sql.Timestamp(cal.getTimeInMillis());
statement.setTimestamp(1, timstamp);
int insertedRecordsCount = statement.executeUpdate();
like image 189
Taky Avatar answered Nov 05 '22 20:11

Taky


First of all, do NOT use string concatenation. Have you ever heart about SQL injection?

Correct way how to do that is to use prepared statement:

Idea is you define statement with placeholders and than you define value for those placeholders.

See @Taky's answer for more details.

like image 44
Betlista Avatar answered Nov 05 '22 18:11

Betlista


dateFormat#format this method returns formatted string not Date object. Database field is DateTime and it is expecting java.sql.Timestamp to be inserted there not String according to docs.

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

Try java.sql.Timestamp object instead of String in query and I'd recommend you to use PreparedStatement.

like image 1
Subhrajyoti Majumder Avatar answered Nov 05 '22 18:11

Subhrajyoti Majumder