jdbc 連結資料庫配置Properties 方法
阿新 • • 發佈:2019-02-06
package com.itxdl.ums.util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
//連線池版本
public class DBUtil2 {
private static BasicDataSource dataSource;
static{
dataSource = new BasicDataSource();
initParameter();
}
public static void initParameter(){ //讀取屬性檔案 Properties prop = new Properties(); try { prop.load(DBUtil2.class.getClassLoader().getResourceAsStream("db.properties")); dataSource.setUsername(prop.getProperty("jdbc.user")); dataSource.setUrl(prop.getProperty("jdbc.url")); dataSource.setPassword(prop.getProperty("jdbc.password")); dataSource.setDriverClassName(prop.getProperty("jdbc.driverClass")); dataSource.setInitialSize(Integer.parseInt(prop.getProperty("jdbc.initSize"))); } catch (IOException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException{ return dataSource.getConnection(); } public static void close(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void main(String[] args) throws SQLException { System.out.println(getConnection()); }
}
properites配置檔案
jdbc.url=jdbc:oracle:thin:@localhost:1521/xe
jdbc.user=system
jdbc.password=123456
jdbc.driverClass=oracle.jdbc.driver.OracleDriver
jdbc.initSize=20