How to insert java.util.Date to Oracle by OraclePrepaidStatement

Hi all,

I am trying to insert the date data to oracle a lot. But all of them works wrong?

Here's a code:

package main;

import oracle.jdbc.driver.*;

import oracledb.OraCon;

import java.text.SimpleDateFormat;

publicclass inmain{

/**

* @param args

*/

publicstaticvoid main(String[] args)

{

OraCon conn =new OraCon();

conn.alloc();

String sql ="insert into test(c_Date, c_Float, c_Int, c_String) values (?,?,?,?)";

java.text.SimpleDateFormat MMddyyyyHHmmss =new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

try

{

OraclePreparedStatement ps = (OraclePreparedStatement)conn.oraconnection.prepareStatement(sql);

String date ="12/12/2006 17:33:01";

java.util.Date ud = MMddyyyyHHmmss.parse(date);

java.sql.Date dd =new java.sql.Date(ud.getTime());

float ff = Integer.parseInt("1");

ps.setDate(1, dd);

ps.setFloat(2, ff);

ps.setInt(3, 4);

ps.setString(4,"This is test");

ps.executeUpdate();

}

catch(Exception e)

{

e.printStackTrace();

}}

}

Then I select from the table.

select to_char(test.C_DATE, 'yyyy-MM-dd HH24:mi:ss')

from test

Its result is:

2006-12-12 00:00:00

I wanna to show 2006-12-12 17:33:01.

How?

[2228 byte] By [Batbold] at [2007-11-26 12:17:14]
# 1
Read the docs: the java.sql.Date holds only the date portion of a given time, not hour, minutes, seconds.
Tonytammaro at 2007-7-7 14:54:26 > top of Java-index,Archived Forums,Socket Programming...
# 2
Use java.sql.Timestamp when inserting into Oracle. This will preserve the time as well as the date segment
NiallMcG at 2007-7-7 14:54:26 > top of Java-index,Archived Forums,Socket Programming...
# 3

Dear NiallMcG,

Thank you very much, It now works fine.

package main;

import oracle.jdbc.driver.*;

import oracledb.OraCon;

import java.sql.Timestamp;

import java.text.SimpleDateFormat;

public class inmain {

/**

* @param args

*/

public static void main(String[] args)

{

OraCon conn = new OraCon();

conn.alloc();

String sql = "insert into test(c_Date, c_Float, c_Int, c_String) values (?,?,?,?)";

java.text.SimpleDateFormat MMddyyyyHHmmss = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

try

{

OraclePreparedStatement ps = (OraclePreparedStatement)conn.oraconnection.prepareStatement(sql);

String date = "12/12/2006 17:33:01";

java.util.Date ud = MMddyyyyHHmmss.parse(date);

float ff = Integer.parseInt("1");

Timestamp ts = new java.sql.Timestamp(ud.getTime());

ps.setTimestamp(1,ts);

ps.setFloat(2, ff);

ps.setInt(3, 4);

ps.setString(4, "This is test");

ps.executeUpdate();

}

catch(Exception e)

{

e.printStackTrace();

}

conn.release();

}

}

mr_bold at 2007-7-7 14:54:26 > top of Java-index,Archived Forums,Socket Programming...