Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date - Insert into database

Tags:

java

date

sql

I need to figure out a way to insert a record with a java.util.Date field into a database and i'm stuck.

Does anyone know how i can do this? Right now i have something like.

        java.util.Date myDate = new java.util.Date("01/01/2009");

        sb.append("INSERT INTO USERS");
        sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) ");
        sb.append("VALUES ( ");
        sb.append("  '" + userId + "'");
        sb.append(", '" + myUser.GetFirstname() + "' ");
        sb.append(", '" + myUser.GetLastname() + "' ");
        sb.append(", '" + myUser.GetSex() + "' ");
        sb.append(", '" + myDate  + "'");
        sb.append(")");

        Util.executeUpdate(sb.toString());

But when i run something like this i get the error: The syntax of the string representation of a datetime value is incorrect.

Heres what the sql statement looks like:

INSERT INTO USERS (USER_ID
    , FIRST_NAME
    , LAST_NAME
    , SEX
    , CRDATE) 
VALUES (   
    'user'
    , 'FirstTest' 
    , 'LastTest' 
    , 'M'
    , 'Thu Jan 01 00:00:00 CST 2009')

Thanks

like image 210
zSynopsis Avatar asked Jul 04 '09 00:07

zSynopsis


People also ask

How to insert date in database in java?

Jakarta EE/Java JEE 8 Web Development(Servlet, JSP and JDBC) You can insert date values in SQL using the date datatype, The java. sql. Date class maps to the SQL DATE type. An integer representing the parameter index of the place holder (?) to which we need to set date value.

How do I insert a date record in SQL?

Always use ANSI default string literal format for date i.e. YYYY-MM-DD like below. INSERT INTO EMPLOYEE (EMPID, FULLNAME, DESIGNATION, JOINING, SAL, DEPTNAME) VALUES(8976, 'JOHN', 'JOE', 'ANALYST', '1990-12-12', 30000, 'Analytics'); It will insert your data in RDBMS i.e. MySQL, PostgreSQL, SQL Server.

What is java SQL date?

A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. To conform with the definition of SQL DATE , the millisecond values wrapped by a java.

Can we convert string to date in java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.


2 Answers

Before I answer your question, I'd like to mention that you should probably look into using some sort of ORM solution (e.g., Hibernate), wrapped behind a data access tier. What you are doing appear to be very anti-OO. I admittedly do not know what the rest of your code looks like, but generally, if you start seeing yourself using a lot of Utility classes, you're probably taking too structural of an approach.

To answer your question, as others have mentioned, look into java.sql.PreparedStatement, and use java.sql.Date or java.sql.Timestamp. Something like (to use your original code as much as possible, you probably want to change it even more):

java.util.Date myDate = new java.util.Date("10/10/2009");
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());

sb.append("INSERT INTO USERS");
sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) ");
sb.append("VALUES ( ");
sb.append("?, ?, ?, ?, ?");
sb.append(")");

Connection conn = ...;// you'll have to get this connection somehow
PreparedStatement stmt = conn.prepareStatement(sb.toString());
stmt.setString(1, userId);
stmt.setString(2, myUser.GetFirstName());
stmt.setString(3, myUser.GetLastName());
stmt.setString(4, myUser.GetSex());
stmt.setDate(5, sqlDate);

stmt.executeUpdate(); // optionally check the return value of this call

One additional benefit of this approach is that it automatically escapes your strings for you (e.g., if were to insert someone with the last name "O'Brien", you'd have problems with your original implementation).

like image 161
Jack Leow Avatar answered Sep 30 '22 02:09

Jack Leow


PreparedStatement

You should definitely use a PreparedStatement. (Tutorial)

That way you can invoke:

pstmt.setDate( 1, aDate );

The JDBC driver will do date-time handling appropriate for your particular database.

Also, a PreparedStatement stops any SQL injection hacking attempts – very important! (humor)

It should look like this:

SimpleDateFormat format = new SimpleDateFormat( "MM/dd/yyyy" );  // United States style of format.
java.util.Date myDate = format.parse( "10/10/2009" );  // Notice the ".util." of package name.

PreparedStatement pstmt = connection.prepareStatement(
"INSERT INTO USERS ( USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE ) " +
" values (?, ?, ?, ?, ? )");

pstmt.setString( 1, userId );
pstmt.setString( 3, myUser.getLastName() ); 
pstmt.setString( 2, myUser.getFirstName() ); // please use "getFir…" instead of "GetFir…", per Java conventions.
pstmt.setString( 4, myUser.getSex() );
java.sql.Date sqlDate = new java.sql.Date( myDate.getTime() ); // Notice the ".sql." (not "util") in package name.
pstmt.setDate( 5, sqlDate ); 

And that's it, the JDBC driver will create the right SQL syntax for you.

Retrieving

When retrieving a Date object, you can use a SimpleDateFormat to create a formatted string representation of the date-time value.

Here is one quick example line, but search StackOverflow for many more.

String s = new SimpleDateFormat("dd/MM/yyyy").format( aDate ); 
like image 20
OscarRyz Avatar answered Sep 30 '22 01:09

OscarRyz