Database Reference
In-Depth Information
java.sql.Date , and to refer to them correctly. But more reasonably, you will have to choose one or the
other. Choose java.util.Date .
One benefit we might garner from using java.sql.Date (not our preferred approach) would be that
we could call ResultSet.getDate() and get a java.sql.Date object directly, without casting. However,
the most important single function that is missing from java.sql.Date is the ability to get the current
time and date. This topic came up in Chapter 7, in the sidebar “A Tale of Two Date Classes.” On the other
hand, with java.util.Date , we simply get a new Date() , and the default constructor builds a Date based
on the current milliseconds value. A second reason to avoid java.sql.Date is that if you decided to
standardize on that Date in an application, you would have to import it from the java.sql package even
in some classes that have no interaction with SQL databases. In those cases, I would argue,
java.sql.Date is out of place.
The format Strings and a SimpleDateFormat class shown in Listing 9-21 are what we need to do date
exchange between Oracle database and Java. This is used in our distribute2Factor() method.
Listing 9-21. Standard Date Exchange Between Oracle Database and Java
import java.text.SimpleDateFormat;
import java.util.Date;
String oraFmtSt = "YYYY-MM-DD HH24:MI:SS"; // use with to_char()
String javaFmtSt = "yyyy-MM-d H:m:s";
SimpleDateFormat ora2JavaDtFmt = new SimpleDateFormat( javaFmtSt );
The next standard practice I propose is that you always exchange dates as Strings / VARCHAR2 s. We
will define analogous formats for dates that allow us to exchange them as strings and rebuild
representative dates on both Java and Oracle Database. On Oracle database, we use the TO_CHAR and
TO_DATE functions; and in Java, we use SimpleDateFormat.parse() and SimpleDateFormat.format()
methods. The standard methods for exchanging dates between Oracle database and Java are presented
in Table 9-2.
Table 9-2. Methods for Exchanging Dates Between Oracle Database and Java
Perspective for Date Exchange
Method Used for Date Representation
SELECT TO_CHAR( SYSDATE,
'YYYY-MM-DD HH24:MI:SS' ) FROM DUAL;
Sending date from Oracle to Java
MY_DATE DATE := TO_DATE( CHAR_DATE,
'YYYY-MM-DD HH24:MI:SS' );
Receiving date string in Oracle from Java
Date javaDate =
ora2JavaDtFmt.parse( rs.getString(1) );
Receiving date string in Java from Oracle
stmt.setString( ora2JavaDtFmt.format( javaDate ) );
Sending date from Java to Oracle
 
Search WWH ::




Custom Search