I make an application based on hibernate,
I just wanna ask,
How to parse this "31/10/13" to Oracle date in Java,
before this, I've try this method
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Date log_date = sdf1.parse(tgl1);
it works, but when I try to make a simple query to search data like this
select * from coreservice where log_date='31-OCT-13';
but I got no data found in result....
Any help will be pleasure :)
Use oracle to_date functionin your query as follows:
select * from coreservice where log_date = to_date('31-OCT-2013','dd/mon/yyyy');
Related
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!
I am using Orientdb with Eclipse and the orientdb-client jar. I use the following statement to read out Messages:
List<ODocument> result = connection.command(
new OSQLSynchQuery<ODocument>(
"SELECT * FROM Message"))
.execute();
At first glance the results looks right, but then i realized that the time i read out from a DATTIME field is wrong.
When i run the query "select * from Message ", the locahost version gives me the following results (just a part of it):
When i run the java snippet from above, the results looks like :
For the formating i use a SimpleDateFormat:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss a");
String time = formatter.format(each.field("Time"));
So why is the hour of the date different ( 2 hours) ? Could it be a Timezone issue?
It because database returns results in database's timezone.
You can see it from studio in section Db->configuration.
Command to update timezone looks like
alter database timezone GMT+6
I'm using Hibernate Search 4.4.0 in Infinispan. I'm trying to search the date of inserting docs. And I have saved date in type String.
This is the definition of date in my class:
private String ins = Constants.dateFormat.format(new Date());
And the dateFormat is:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Now I mapping this field like:
mapping.entity(Entity.class)
.property("ins", ElementType.FIELD).field().analyze(Analyze.NO);
I have verified that there are objects in my cache whose date property is 2012-09-17 14:28:32.0. But when I use query like:
Query query = queryBuilder.keyword().onField("ins").matching("2012-09-17").creatQuery();
to search in cache, there is no result.
Is there something I messed up??
I'm not an expert in Hibernate Search, but I think that instead of
.analyze(Analyze.NO)
you shall write
.analyze(Analyze.NOT_TOKENIZED)
or alike
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 am using sqljdbc4.jar to connect SQL Server from my java application. I have a date field in my table. It works normally when I check from Sql Server Management Studio. But in java, every date is 2 day missing.
For example;
my date : 2012-01-10
date in java : 2012-01-08
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM table1", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery();
rs.next();
System.out.println(rs2.getDate("dateCol").toString());
Why?
I just tried sqljdbc4.jar version 4, it fixed. Also there is no problem with version 2. Only bugged version is 3. Download link for version 4.
Thanks for answers.
which version of SQL Server and which datatype are you using? There are 6 "date and time" data types on SQl Server 2008:
date
datetimeoffset
datetime2
smalldatetime
datetime
time
maybe the one you are using is not supported in Java or by the drive you are using. Specially if you are using Date which is new in SQL Server 2008
like #Eugenio Cuevas said
please try formatting the date
Could you try using SimpleDateFormat with yyyy.MM.dd format instead of .toString method?
because looking at you date example ; may be its like a problem i faced before
the difference is 2 day because
1- 2012-01-10 and 2012-01-08 yyyy-mm-dd
2- 12-01-10 and 12-01-08 yy-mm-dd
that what caused my problem
I was faced with somewhat similar problem couple of weeks. I had to save a java date in an oracle table which is typed sql date. You can not directly cast a java date to sql date. The following is what I did.
java.util.Date jDate = myObj.getDate();
java.sql.Date sDate = new java.sql.Date(jDate.getTime());