1. 程式人生 > >獲取資料庫連線的公用方法

獲取資料庫連線的公用方法

public final class DriverUitl {


/ *c3p0 的方式   讀取配置檔案 連線資料庫的方法
前提:1.匯入相應的 jar 包(c3p0-0.9.1.2.jar)
         2 . src 路徑下存在 c3p0-config.xml 檔案



*   配置檔案 命名 為 : c3p0-config.xml
*   <named-config name="Datbasec3p0">
*/
private static DataSource ds =null;
static {
//讀取c3p0配置檔案
ds = new ComboPooledDataSource("Datbasec3p0");
}
public static Connection getConnectionC3P() throws SQLException{
return ds.getConnection();
}





/*
 * 讀取properties 檔案獲取連線字串的 公用 
 * 獲取資料庫連線的方法


* 獲取資料庫連線的公用方法
*/
public static Connection getConnection() throws Exception {

// 1建立讀取配置檔案的 物件
Properties pros = new Properties();
  // 1 獲取檔案流 因為是靜態中, 使用以下格式
InputStream inps = DriverUitl.class.getClassLoader().getResourceAsStream("jdbc.properties");
  // 2 讀取檔案流
pros.load(inps);
  // 3為 連線字串賦值
String driver = pros.getProperty("driver");
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");


// 2 載入驅動
Class.forName(driver);
// 3 獲取資料庫連線 並將其返回
return DriverManager.getConnection(url, user, password);


}


/*
* 關閉流的公用方法
*/
public static void close(ResultSet resultSet,
PreparedStatement statement, Connection connection) {

// 關閉 ResultSet流
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
System.out.println("關閉ResultSet 物件出現錯誤!");
e.printStackTrace();
}
}


// 關閉 PreparedStatement 流
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
System.out.println("關閉PreparedStatement 物件出現錯誤!");
e.printStackTrace();
}
}


// Connection 流
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.out.println("關閉Connection 物件出現錯誤!");
e.printStackTrace();
}
}


}


}