JDBC連接DB2、Oracle、MySQL、PostgreSQL,並取得當前時間得實用代碼:
package com.terac.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import Java.sql.Statement; public class DBTest { public static void main(String[] args) { try { String user = "user"; String password = "passWord"; String driver = "COM.ibm.db2.jdbc.Net.DB2Driver"; //"oracle.jdbc.driver.OracleDriver"; //"com.mysql.jdbc.Driver"; //"org.postgresql.Driver"; String url = "jdbc:db2://localhost/a"; //"jdbc:Oracle:thin:@localhost:1521:a"; //"jdbc:MySQL://localhost/a"; //"jdbc:postgresql://localhost:5740/a"; String sql = "SELECT current timestamp FROM sysibm.sysdummy1"; //"SELECT sysdate FROM dual"; //"SELECT now()"; //"SELECT current_timestamp"; Class.forName(driver).newInstance(); Connection c = DriverManager.getConnection(url, user, passWord); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { System.out.println(rs.getString(1)); } } catch (Exception e) { e.printStackTrace(); } } }