简体   繁体   中英

How to convert Java String to Teradata DATE and Timestamp

My java code generates two Strings :

String myDate = "10/10/2013";
String myTimestamp = "2013-10-09 14:30:20"; 

I need to feed these values to a prepared statement , so that I could upload them using jdbc to Teradata

Here is what I tried :

String in = " INSERT INTO " + myTab + " VALUES (?,?) "; 

PreparedStatement prst = null; 
prst = connection.prepareStatement(in); 

   // add date
   prst.setDate(1, (Date) new SimpleDateFormat("MM/dd/yyyy").parse(myDate));

   //add timestamp
   prst.setDate(2, (Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(myTimestamp)); 

The above code compiles but does not work. I get an empty string error . How can I convert a String into Teradata types DATE, TIMESTAMP in order to add them to the prepared statement ?

You could use the java.sql.Date constructor that takes a long , by using Date#getTime() and changing from

prst.setDate(1, (Date) new SimpleDateFormat("MM/dd/yyyy").parse(myDate));

to something like

prst.setDate(1, new java.sql.Date(new SimpleDateFormat("MM/dd/yyyy")
    .parse(myDate)).getTime());

and the other one

prst.setDate(2, new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    .parse(myTimestamp)).getTime());

Try this:

prst.setDate(1, new java.sql.Date(new SimpleDateFormat("MM/dd/yyyy").parse(myDate).getTime()));

This will convert your date then create a new sqlDate.

prst.setTimestamp(2, new java.sql.Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(myTimeStamp).getTime());)

for the timestamp use setTimeStamp not setDate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM