C3P0訪問資料庫工具類
阿新 • • 發佈:2019-02-15
建立配置檔案:c3p0-config.xml(必須放在src目錄下)
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property >
<property name="maxPoolSize">20</property>
</default-config>
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc</property >
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</named-config>
<named-config name="oracle">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</named-config>
</c3p0-config>
建立工具類
public class C3P0Util {
private static DataSource ds = new ComboPooledDataSource();
/**
* 獲取連結
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/**
* 獲取資料來源
* @return
*/
public static DataSource getDataSource() {
return ds;
}
/**
* 關閉資源
* @param rs
* @param st
* @param con
*/
public static void release(ResultSet rs, Statement st, Connection con) {
try {
if (rs != null) {
rs.close();
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (st != null) {
st.close();
st = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
測試程式碼
public class C3p0Test {
@Test
public void testAdd(){
Connection con =null;
Statement st =null;
try{
con=C3P0Util.getConnection();
st=con.createStatement();
System.out.println(st);
}catch(Exception e){
e.printStackTrace();
}finally{
C3P0Util.release(null, st, con);
}
}
}
需要的依賴包
- c3p0-0.9.1.2
- c3p0-0.9.1.2-jdk1.3
- c3p0-oracle-thin-extras-0.9.1.2(相容oracle)
- mysql-connector-java-5.0.8-bin