Query gives different output on different OS - java

I have written the following function in Java. This function returns current timestamp by executing a query. The function code is as follows :
private String getTimeStamp(){
String timeStamp=null;
try{
String strQuery="select current_timestamp";
PreparedStatement pmtQuery=con.prepareStatement(strQuery);
ResultSet rsQuery=pmtQuery.executeQuery();
rsQuery.next();
timeStamp=rsQuery.getString(1);
JOptionPane.showMessageDialog(null, "Value of timeStamp : "+timeStamp);
}catch(SQLException e){
System.out.println("SQL Exception in the getTimeStamp()");
}
return timeStamp;
}
When I use this function on windows It gives proper out put and works fine.
Ex.
If execute above function in widows it gives timestamp like ex. 2011-06-01 17:05:03
but when I execute this function in Debina linux it gives timestamp as
2011-06-01 17:05:03.0
It appends .0 to timestamp
Please guide me in this problem
1.why such different output comes on different system?
2.How to avoid this problem?
3.How to solve this problem?
I am using following configurations
windows
windows 7, Mysql database, Java 6
Linux
Debian linux, Mysql Database, Java 6
Thank You!

Use this
SELECT DATE_FORMAT(CURDATE(), '%d/%m/%Y %hh%mm%ss')
Note:
I wonder why you are querying to get the currentDate

The problem probably are different (default) settings of the JDBC drivers.
I would prefer fetching the timestamp as a Timestamp (subclass of java.util.Date):
import java.sql.Timestamp;
...
Timestamp timeStamp;
...
timeStamp = rsQuery.getTimestamp(1);
This way you can control how to format it in the Java code as/if needed (e.g. using SimpleDateFormat or String.format).

It's not portable, but you can use the DATE_FORMAT function:
SELECT DATE_FORMAT(CURRENT_TIMESTAMP, '%d/%m/%Y %h:%i:%s');
Documentation is here

you can also use
SimpleDateFormat
Its a simple date formatter.

Related

How to get Date AND Time from Oracle database, using Hibernate?

I have been given some code to work on. I need to modify the existing code to return an extra column. Using the tool, SQLDeveloper, I can see an example record (notice Date AND Time information is present):
30-NOV-17 15:54:00
The code that I have been given to work on does the following:
// Create a Hibernate query (Oracle SQL query)
Query query = session.createSQLQuery(<NATIVE_SQL_QUERY_HERE>);
List<Object[]> rawDataRows = query.list();
if (rawDataRows != null) {
for(Object[] rawDataRow : rawDataRows) {
// I am trying to get the Date AND Time here
Timestamp ts = (Timestamp) rawDataRow[7];
}
}
The problem is that I get an error when I try this approach (Cannot cast java.sql.Date to Timestamp).
When I access the data without the cast (just get the data in a Date object), I DO NOT get the Time information. And I need to have BOTH.
So far, nothing I have tried has worked - other posts have similar issues, but they are not quite the same.
Any advice/suggestions much appreciated - THANKS!
You can use this code:
....
Calendar calendar = Calendar.getInstance();
calendar.setTime(rawDataRow[7]);
Timestamp ts = new Timestamp(calendar.getTimeInMillis());
...

JPA CreateNativeQuery returns wrong date

We recently updated a project from using Hibernate 4 to Hibernate 5.2, and with that came the need to update all of our Criteria to use JPA. For the most part things are in working order, but I have one query that is no longer behaving. One of the fields on the table we are querying is of type DATE in the database.
When I query directly on the table I get back the date- say it is "2017-04-20." However, when I run the same query on our development server, using JPA's createNativeQuery, I get back the date "2017-04-19"
I don't think this is an issue with the query as I run the exact same query both through a mysql terminal and through java and get different results. The query that I run is the one that is logged in my below example. I think it may be a timezone issue as I don't have this problem on my local environment, just on my dev server, but it also wasn't a problem until we updated to the new versions of Hibernate.
public List<ResponseDTO> getDashboardData(String date, Integer page, Integer pageSize, AbstractDashboard dashboard) {
List<ResponseDTO> processed = new ArrayList<ResponseDTO>();
String query = getDashboardQuery(date, dashboard);
logger.info("Dashboard Query: " + query);
List<Object[]> raw = createNativeQuery(query).getResultList();
return raw.stream().map(r->new ResponseDTO(r)).collect(Collectors.toList());
}
And the constructor of my DTO object:
public ResponseDTO(Object[] r) {
this.date = ((Date) r[0]).toLocalDate();
System.out.println(this.date.toString());//This date does not match what is in the db.
this.type = (String) r[1];
this.label = (String) r[2];
this.value = (Double) r[3];
}
Edit:
I think it's actually an issue with the java.sql.Date type, because I tried printing that out on my dev server and it also returns "2017-04-19" instead of the 20th. I don't get why this doesn't match the results when I run the query in a mysql console, it seems like they should be the same to me.
Try another JDBC driver
Ok, I got it working. For what it's worth, this seems like complete madness to me. The "Aha!" moment came while reading this answer to a different question.
Since it is the mysql driver that dictates how the date is parsed in the system. I rolled back my mysql driver as that was one of the packages that I updated. Suddenly everything behaved as expected.

Caused by: java.lang.ClassCastException: java.sql.Timestamp cannot be cast to java.sql.Date

I am getting the below given error for the following code snippets:
try {
cRows = new CachedRowSetImpl();
while(cRows.next())
{
MyClass myClass = new MyClass();
myClass.setPrevDate(cRows.getDate("PREV_DATE")); // In debug mode, the error was throwing when I press Resume from here.
}
}
Error:
Caused by: java.lang.ClassCastException: java.sql.Timestamp cannot be cast to java.sql.Date
In the database, the datatype for the column is DATE only. I am not able to figure out where the Timestamp is coming here.
Obsolete:
Use java.util.Date for the field. java.sql.Timestamp is a direct subclass of it. As is java.sql.Date - that strips the time part. Why the java database driver takes DATE to be Timestamp is a bit weird. What is the database vendor? Did you specify a length or so? Are indeed only dates stored?
Researched:
I looked into CachedRowSetImpl.java, and Oracle's docs and Oracle does everything fine (java.sql.Date, java.sql.Time, java.sql.Timestamp convertible).
The CachedRowSetImpl does simply cast the DATE's Object (and getObject is likely to return the high resolution Timestamp - with time) to java.sql.Date, and that's wrong.
So override or substitute this sun's class.
/*
* The object coming back from the db could be
* a date, a timestamp, or a char field variety.
* If it's a date type return it, a timestamp
* we turn into a long and then into a date,
* char strings we try to parse. Yuck.
*/
switch (RowSetMD.getColumnType(columnIndex)) {
case java.sql.Types.DATE: {
long sec = ((java.sql.Date)value).getTime();
return new java.sql.Date(sec);
}
I have done a research on this issue and found some useful links. I found this confusion between DATE and TIMESTAMP is JDBC Driver specific. And most of the links suggest the use of -Doracle.jdbc.V8Compatible=true. For my JBoss I have set this in run.bat and the issue got resolved.
https://community.oracle.com/thread/68918?start=0&tstart=0
http://www.coderanch.com/t/90891/JBoss/oracle-jdbc-Compatible-true
https://community.oracle.com/message/3613155
The oracle doc shares different solutions:
Alter your tables to use TIMESTAMP instead of DATE. This is probably
rarely possible, but it is the best solution when it is.
Alter your application to use defineColumnType to define the columns
as TIMESTAMP rather than DATE. There are problems with this because
you really don't want to use defineColumnType unless you have to (see
What is defineColumnType and when should I use it? ).
Alter you application to use getTimestamp rather than getObject. This
is a good solution when possible, however many applications contain
generic code that relies on getObject, so it isn't always possible.
Set the V8Compatible connection property. This tells the JDBC drivers
to use the old mapping rather than the new one. You can set this flag
either as a connection property or a system property. You set the
connection property by adding it to the java.util.Properties object
passed to DriverManager.getConnection or to
OracleDataSource.setConnectionProperties. You set the system property
by including a -D option in your java command line.
java -Doracle.jdbc.V8Compatible="true" MyApp
Here is the link: http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#08_00

Resultset getDate() returned incorrect date value

This error happen in my application when I try run the following:
SELECT send_day FROM types WHERE ID_TYPE = 4
The query execution returned that date with 2 days before of column value.
The recovering of this value in Java app is this:
java.sql.Date dataSQL = retorno.getDate(1);
I'm using SQLJDB4.0 driver and database version is 2008.
Some answers for post comments:
The value of database is 2013-08-22 and the return is 2013-08-20
My timezone is UTC-03:00 . In the database, I exec the following command: select SYSDATETIMEOFFSET() which return: 2013-08-22 11:49:12.4010367 -03:00
I updated the SQLJDBC for 4-4.0 version and the problem has been resolved.

Trouble when inserting time and date to db using Java

Here's my code:
uprs.moveToInsertRow();
uprs.updateString("Sender", myName);
uprs.updateString("Receiver", withWho);
uprs.updateString("Message", myMessage);
//uprs.updateString("Time",****);
uprs.insertRow();
Things go perfectly when adding the non-time data into the database.
But I am struggling how to add the current date and time into the database.(Ms SQL 2008)
Is there any expert can tell me how to organize the code about getting the current time and date and insert them into the db?
The data type of Time in my db is "datetime".
Thank you!
For a date/time type you should use updateTimestamp instead of updateString

Categories

Resources