Insert datetime string from java in MySQL - java

Hi all i have a problem in a insert query.
I get datetime from java with:
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
String strDate = sdfDate.format(now);
p.s: I have try a sysout on strDate and it is correct.
I read a question, like that, where to enter in MySQL datetime must make a query like this:
INSERT INTO tracks (in) VALUES (STR_TO_DATE( ? ,'%Y-%m-%d %r'))
Where '?' is the string containing the date, but it don' t work.
Can anyone help me?
UPDATE: MySQL Server 5.7

You have use current time. So you can do it simply with NOW().
INSERT INTO tracks (`in`) VALUES (NOW())
OR
You can do this way
java.sql.Timestamp now = new java.sql.Timestamp(new java.util.Date().getTime());
PrepStmt.setTimestamp(1, now);

I have found the problem.
The name "in" for the DateTime field is not accepted.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'in, session) VALUES (1, NOW(), "abc")' at line 1.
'in, session)
I have try to rename it in "indate" and the query:
INSERT INTO tracks (fk_utenza, indate, session) VALUES (1, NOW(), "abc");
works well!

Related

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.

Wrong date selection in SQL

I'm working with Hibernate 4.3.8.Final, Primefaces 6.0 and MySQL Database 5.7.13.
I have a table in the database with this structure:
CREATE TABLE `rents` (
`rent_code` INT NOT NULL AUTO_INCREMENT,
`rent_daystart` datetime default NULL,
`rent_dayend` datetime default NULL,
PRIMARY KEY (`rent_code`)
) ENGINE = innodb CHARACTER SET utf8 COLLATE utf8_unicode_ci;
And the following data extracted with Squirrel with the following SQL:
select * from rents
rent_code | rent_daystart | rent_dayend
1 | 2016-11-30 16:03:00.0 | 2016-12-01 16:03:00.0
In my Java bean I have the following function:
public List<Object> getRents(java.util.Date iniDate, java.util.Date endDate){
String SQL="select rent_code from rents where rent_daystart < :inidate and rent_dayend > :enddate";
List<Object> allRecords = null;
Session sesion=HibernateUtil.getSessionFactory().openSession();
try {
sesion.beginTransaction();
Query query = sesion.createSQLQuery(SQL).setDate("inidate", iniDate).setDate("enddate", endDate);
allRecords = query.list();
sesion.getTransaction().commit();
sesion.close();
}
catch (HibernateException he) {
//exception control code
};
return allRecords;
}
I execute the web APP debugging and the dates that the function receives are:
**inidate** = 'Wed Nov 30 17:54:00 CET 2016'
**enddate** = 'Wed Nov 30 18:54:00 CET 2016'
And it returns NO RECORD AT ALL.
If I execute the same SQL in squirrel that way:
select rent_code from rents where rent_daystart < '2016-11-30 17:54:00' and rent_dayend > '2016-11-30 18:54:00'
It returns one record.
I suspect that this is a data type problem or something like that, but after researching in the web it is not clear to me.
May someone help me?
Thanks in advance!
The java.util.Date class doesn't handle time zones. Unless you are using the same time zone in both your Date instance and the database fields, you can easily mismatch the time zones creating the behavior that you are seeing. Try and display the java Date in UTC format, and look at your database date in UTC format, and see if they line up like you expect.
If it is a date format mismatch between the values passed from the code and the values expected in database then use SimpleDateFormat to change the format of the date values before passing on to databse
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = dt.parse(iniDate);
Well, I have found the problem. As stated in Compare Date Java to DateTime Column in database table using SQL I was using the ".setDate" function to set the dates, such function truncates the time part, that was the problem. Now I'm using the ".setTimestamp" that uses both, date and time parts.
Thanks to all for your help, I have learned a lot about TimeZones!

java to format date and to return it as date object

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

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+"')");

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

Categories