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
this is the code I used to save date into the database using jdbc works fine for me
pst
is a variable for preparedstatementtxtdate
is the name for the JDateChooserBefore 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 usejava.sql.Date
orjava.sql.Timestamp
. Something like (to use your original code as much as possible, you probably want to change it even more):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).
You can use it to insert variables into sql query.
Use prepared statements, they have methods to set correctly parameters for each native Java type.
Look at the api for setDate and the examples
you can use this code date and time time is 24 h
if you are using mysql .. you can save date as "2009-12-31" for example.
update person set birthday_date = '2009-12-31'
but i prefer to use jdbc although you have to create java.sql.Date ...
*Date is kind of evil in this world ... :)