21 rs = stmt.executeQuery("SELECT * from user_tables");
22 System.out.println("Got results:");
23 // position rs after the last row
24 rs.afterLast();
25 while (rs.previous()) {
26 String tablename = rs.getString("table_name");
27 System.out.println("Table_Name = " + tablename);
28 }
29 System.out.println("Done.");
30 } catch (Exception e) {
31 e.printStackTrace();
32 } finally {
33 if (conn != null) {
34 try {
35 conn.close();
36 } catch (SQLException e) {
37 }
38 }
39 }
40 }
41 }
6. 向数据库的表中插入日期型和Timestamp类型的数据,同时执行查询并取出刚刚插入的日期和Timestamp类型的数据。
1 public class MyTest {
2 private static Connection getConnection() throws SQLException,
3 ClassNotFoundException {
4 Class.forName("oracle.jdbc.driver.OracleDriver");
5 Properties conProps = new Properties();
6 conProps.put("user", "sys");
7 conProps.put("password", "helloworld");
8 conProps.put("internal_logon", "sysdba");
9 return DriverManager.getConnection(
10 "jdbc:oracle:thin:@//192.168.1.101:1526/OraHome", conProps);
11 }
12 public static void main(String[] args) throws ClassNotFoundException {
13 Connection conn = null;
14 Statement stmt = null;
15 PreparedStatement pstmt = null;
16 ResultSet rs = null;
17 try {
18 // 1. 创建带有各种日期类型的表。
19 String createTable = "CREATE TABLE TestDates ("
20 + "id VARCHAR2(10),"
21 + "date_column DATE," + "time_column DATE,"
22 + "timestamp_column TIMESTAMP(6))";
23 conn = getConnection();
24 stmt = conn.createStatement();
25 stmt.execute(createTable);
26 stmt.close();
27 // 2. 插入各种日期类型的数据
28 String insertRecord = "insert into TestDates(id, date_column, "
29 + "time_column, timestamp_column) values( , , , )";
30 pstmt = conn.prepareStatement(insertRecord);
31 pstmt.setString(1, "001");
32 java.util.Date date = new java.util.Date();
33 long t = date.getTime();
34 java.sql.Date sqlDate = new java.sql.Date(t);
35 java.sql.Time sqlTime = new java.sql.Time(t);
36 java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(t);
37 System.out.println("Begin inserting.");
38 System.out.println("sqlDate = " + sqlDate);
39 System.out.println("sqlTime = " + sqlTime);
40 System.out.println("sqlTimestamp = " + sqlTimestamp);
41 pstmt.setDate(2, sqlDate);
42