表结构:
[sql] view plaincopy
1. create table TEST(
2. ID INTEGER,
3. BIRTHDAY TIMESTAMP
4. );
使用JDBC将日期插入到TIMESTAMP类型字段
[java] view plaincopy
1. import java.sql.Connection;
2. import java.sql.DriverManager;
3. import java.sql.PreparedStatement;
4. import java.sql.SQLException;
5. import java.text.SimpleDateFormat;
6. import java.util.Date;
7.
8. public class Test {
9.
10. static {
11. try {
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13. } catch (ClassNotFoundException e) {
14. e.printStackTrace();
15. }
16. }
17.
18. /**
19. * 获得Connection
20. *
21. * @return
22. */
23. public static Connection getConnection() {
24. Connection conn = null;
25. try {
26. conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/orcl", "root", "root");
27. } catch (SQLException e) {
28. e.printStackTrace();
29. }
30. return conn;
31. }
32.
33. public static void main(String[] args) throws SQLException {
34. // TODO Auto-generated method stub
35. PreparedStatement pst = null;
36. Connection conn = getConnection();
37. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
38. String myDate = df.format(new Date()); //当前时间
39. String sql = "insert into test(id,birthday) values('1',to_timestamp('" + myDate + "','yyyy-mm-dd hh24:mi:ss'))";
40. pst = conn.prepareStatement(sql);
41.
42. pst.executeUpdate();
43. // 省略IO流close
44. }
45.
46. }
使用to_timestamp将字符型转成timestamp
更多精彩文章请留意http://www.cmxiaodou.com/union