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);
Related
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.
I have a pojo class in which one of the field is date. Here I am using hibernate to insert values into the db using these pojos.
I have set the current date value for this property and I am inserting the value to the DB. Here I need to generate the insert script programaticaly. I have done this and i am printing the insert statement in the console. But while printing in the console the date is shown as Fri Jun 07 04:49:07 ACT 2013 and the insert statement is
INSERT INTO tables (dates)values('Fri Jun 07 04:49:07 ACT 2013');
I don't want to generate the script like this i need it as
INSERT INTO tables (dates)values('2013-06-07');
I know We can use simple date formatter but i need this as date to set the POJO value. So if it is String it will not be set into the object.
I am forming the query as below
StringBuffer columnName = new StringBuffer();
columnName.append("insert into Tables values ('"+obj.getdates()+"')");
Before i used logger and at that time the query was formed and i think hibernate took care of that formatting because after inserting the query was formed as
INSERT INTO tables (dates)values('2013-06-07');
But now by hardcoding it is giving the above query whcih is not getting executed as the date value is not correct.
Can anyone help me here. Also in the case of hibernate whether formatting is done by hibernate or at the backend whether it is converting automatically
Thanks
convert your date into java.sql.Date
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
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+"')");
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());
I'm looking at some code that basically does the following:
ResultSet rs = ps.executeQuery();
String myDateStr = rs.getString("MY_DATE"); //field is of type Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'.0'");
Date myDate = sdf.parse(myDateStr);
On some environments the last line works, and on others it throws an Unparseable date exception. It looks like on some systems the default date format is 2013-01-25 00:00:00.0, and on others 2013-01-25 00:00:00.
The JVM, OS and Oracle version are different between the environments (all use Oracle and run on a unix variant though).
Changing the code might be complex. I'm wondering if there is an environment variable or similar that can be set to make the date format returned from rs.getString() consistent?
try this:
ResultSet rs = ps.executeQuery();
Date myDate = rs.getDate("MY_DATE");
or this :
ResultSet rs = ps.executeQuery();
String myDateStr = rs.getString("MY_DATE");
Date myDate = valueOf(myDateStr);
More about date: http://docs.oracle.com/javase/7/docs/api/java/sql/Date.html
More about ResultSet : http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
Instead of using
String myDateStr = rs.getString("MY_DATE")
you should use
Timestamp timestamp = rs.getTimestamp("MY_DATE");
JDBC / Database will handle the date transformation for you.
If the field is of type Date, then read it as a java.sql.Date and do whatever conversion you need after that. Otherwise you're at the mercy of the database implementation.
For the Oracle JDBC driver I am using, the format is hard-coded in the driver library, so should only differ across systems if different driver versions are in use.
See my attempt to get an answer to the same question here: Where is the date format specified when reading a date as a string from JDBC ResultSet.
(Apologies for asking a separate question, but as your question had been answered multiple times with the ever-helpful "just don't do that" response, I tried again...).