Java: Insert into a table datetime data - java

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.

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();

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.

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.

This is because you are trying to save String date value to Date type DB field.
convert it to Data dataType
You can also use the datetime "unseparated" format yyyymmdd hh:mm:ss

You could use Joda framework to work with date/time.
It maps own date/time types to Hibernate/SQL types without problem.
When you set parameters in HQL query joda carries about right type mapping.

If you want to store current date and time then you should use MYSQL inbuilt method NOW().
for brief documentation refer http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html . so your code will be like.
INSERT INTO Companies CreatedOn VALUES(NOW())"
However If you want to do it using java Date-util then it should be
Calendar cal = Calendar.getInstance();
java.sql.Timestamp timestamp = new Timestamp(cal.getTimeInMillis());

Related

How to convert "2019-08-07T14:00:00-0400" to SQL DATETIME format in Java?

I couldn't pass in 2019-08-07T14:00:00-0400 to a stored procedure in SQL Server that takes a param in DATETIME.
So how can I convert it to this format YYYY-MM-DD HH:MM:SS.SSS in Java prior to calling the stored procedure?
You can make use of SimpleDateFormatclass for reference visit here
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
Date date = df.parse("2019-08-07T14:00:00-0400");
You will get java.util.Date object in return which in turns you can use to store in database.
If you want to convert it in SQL queries you can use below query.
declare #abc nvarchar(19)='2019-08-07T14:00:00-0400'
select CONVERT(DATETIME,convert(varchar, #abc,121))

Java: SQL date format

Is there any to assign SQL date directly instead of converting through SimpleDateFormat and parse to sql date. I am reading few date fields from a file lets say 03/09/2017 and I also have its oracle equivalent format defined as a field definition mm/dd/yyyy.
I am reading the date and its format through Java and inserting to Database. Currently I am assigning the date format to SimpleDateFormat and parsing the date read from file and converting to SQL date as follows.
SimpleDateFormat YMDFmt = new SimpleDateFormat("mm/dd/yyyy");
// This is not hardcoded field.
// Its field definition will be directly assigned as defined. In this case it is mm/dd/yyyy
Date date;
String datefield="03/09/2017";
date=YMDFmt.parse(datefield);
java.sql.Date sqldt= new java.sql.Date(date.getTime());
Here my problem is due to varying formats, mm is treated as minutes in java where as it is month in oracle. I will have to change to 'MM' to make it work in java but in my scenario i dont know the original format of date. i will have to read the format and parse accordingly? Please advise if there is anyway to just convert oracle format to equivalent java format (mm/dd/yyyy to MM/dd/yyyy and so on) or any other solution. Thank you.
If your database is Oracle, you can change your prepared statement so that it includes a TO_DATE call instead of the date itself.
So, if your current insert statement is something like
String sql = "INSERT INTO foo (datefield) VALUES (?)";
PreparedStatement stmt = con.prepareStatement(sql);
And you use something like stmt.setDate(1,sqldt) to fill in the value, then you can change it into something like
String sql ="INSERT INTO foo (datefield) VALUES (TO_DATE(?,?))";
PreparedStatement stmt = con.prepareStatement(sql);
And use
String oracleFormat = "mm/dd/yyyy"; // Not hard-coded in real life
String dateStr = "03/09/2017"; // Not hard-coded in real life
stmt.setString(1,dateStr);
stmt.setString(2,oracleFormat);
stmt.executeUpdate();
In this case, Oracle will convert the string into a date for you, instead of having Java do that.
Pay attention to changing all the other parameter numbers to fit.

SQL insert date into database

I use java.util.Date to get the date and I get the date format like this
Sat Jun 29 11:07:25 CDT 2013
When I try to insert it into the database using
String QueryString = "INSERT INTO db (day) Values ('"+d+"');";
st.executeUpdate(QueryString);
I get this
"Conversion failed when converting date and/or time from character
string."
How can I insert that type of date into the db?
Should I declare it as a string?
how can i insert that type of date into the db? should i declare it as a string?
No - you should avoid even the string conversion you currently have. You shouldn't build your SQL dynamically like that - it's a recipe for SQL injection attacks, hard-to-read code, and conversion failures.
Instead, use a PreparedStatement and set the parameter using setDate:
// TODO: Closing the statement cleanly in a finally block or try-with-resources
PreparedStatement pst = conn.prepareStatement("INSERT INTO db (day) Values (?)");
pst.setDate(1, new java.sql.Date(d.getTime()));
pst.executeUpdate();
Note that java.sql.Date is a subclass of java.util.Date, but they're somewhat different. It's never been clear to me which time zone is used to convert the given instant in time into a real date - and the documentation is less than helpful. It's broken by design in my view, but that's a different matter. You can use another setDate overload which accepts a Calendar - which is used for the time zone. It's still all horribly unclear, but hopefully you can get the result you want.
Use java.sql.Date to be compatible with the databse
Alternatively, use an updatable ResultSet:
ResultSet rs = conn.createStatement("select day from db", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs.moveToInsertRow();
rs.updateDate(1, yourJavaSqlDateObject);
rs.insertRow();
rs.first();
Though, depending on your driver/database, there may be a write-lock on the table.
Date formatting should be done on output, not input. Let the database decide how best to store the date.
You could use SimpleDateFormat to format your Date object
Date d = Calendar.getInstance().getTime(); //Your date
String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
String QueryString = "INSERT INTO db (day) Values ('"+dateString+"');";
st.executeUpdate(QueryString);

Error while storing jXDatePicker1 Date value in database

I am using swingxLabs' component jXDatePicker1 to pick date in a graphical format and trying to store it in the database made in derby. My code was this:
Date date=jXDatePicker1.getDate();
PreparedStatement statement = connect
.prepareStatement("INSERT INTO BILLING (DATE, DHRNUMBER) VALUES('"+date+"', "+dhrNumber+")");
The error which i am getting is:
java.sql.SQLDataException: The syntax of the string representation of a datetime value is incorrect.
Am i doing it right? Or there can be some other way to solve this.
Thanks
Derby's built-in DATE datatype supports a short list of string formats: http://db.apache.org/derby/docs/10.9/ref/rrefsqlj18730.html
Since you are using PreparedStatement, the best thing to do is to prepare the statement
INSERT INTO BILLING (DATE, DHRNUMBER) VALUES(?,?)
and then substitute your actual values using the setDate() and setInt() methods from:
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
This alternative totally worked for me:
Date d=jXDatePicker1.getDate();
System.out.println(d);
DateFormat df=new SimpleDateFormat("MM/dd/yyyy");
String date=df.format(d);
System.out.println(date);
PreparedStatement statement = connect
.prepareStatement("INSERT INTO BILLING (DATE) VALUES('"+date+"')");

request.getParameter String value pass as date to java

In my JSP page I have a field which is date and when I getting as request.getParameter("dateVal"); gives me
15-Dec-2012 12:21.
I would like to pass this value to my database procedure and insert/update into table.
How can I pass the value as setDate using prepareCall to database?
Thanks
First step would be using SimpleDateFormat to parse it to a fullworthy java.util.Date instance in the controller:
Date date = new SimpleDateFormat("dd-MMM-yyyy HH:mm.", Locale.ENGLISH).parse(dateVal);
Then you can just create a java.sql.Date around its time in the database layer:
statement.setDate(1, new java.sql.Date(date.getTime()));
Unrelated to the concrete problem, please note that java.sql.Date doesn't remember the time part. If you have actually a DATETIME or TIMESTAMP field in the DB and not a DATE field, then rather use setTimestamp() with a java.sql.Timestamp instead. This way the time part will also be stored.
#BalusC 's answer is perfect. But as an alternative solution you can use the function provided by database to convert String to Date while querying. For example(in case you use Oracle),
to_date(date_in_String, format)
Try this :
new SimpleDateFormat("dd-MM-yyyy HH:mm").parse(mydate);

Categories