日期:2014-05-16  浏览次数:20484 次

JDBC 连接数据实例
1、JDBC连接数据库实例 try{}catch{}finally{}
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 conn = DriverManager.getConnection(url, user, password);
	Statement stmt = conn.createStatement();
	ResultSet rs = stmt.executeQuery(sql);
	while (rs.next()) {
		System.out.println(rs.getString(1));
	}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (stmt != null) {
			try {
					stmt.close();
				} catch (SQLException e) {
					logger.error(e.getMessage(), e);
				}
				stmt = null;
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error(e.getMessage(), e);
				}
				conn = null;
			}
	}
	}
}