1.导入jar包文件,并添加路径
2.写好配置文件
3.工具类代码JDBCUtils
4.运用
1.导入jar包文件,并添加路径
2.配置文件
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/stus</property>
<property name="user">root</property>
<property name="password">1234</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
</c3p0-config>
3.工具类代码
JDBCUtils:
package com.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtils {
static ComboPooledDataSource dataSource =null;
static{
dataSource = new ComboPooledDataSource();
}
**public static DataSource getDataSource(){
return dataSource;
}**
public static Connection getConnection() throws SQLException{
return dataSource.getConnection();
}
public static void close(Connection con,Statement stat){
if(stat != null){
try{
stat.close();
}catch(SQLException ex){};
}
if(con != null){
try{
con.close();
}catch(SQLException ex){};
}}
public static void close(Connection con,Statement stat,ResultSet rs){
if(stat != null){
try{
stat.close();
}catch(SQLException ex){};
}
if(con != null){
try{
con.close();
}catch(SQLException ex){};
}
if(rs != null){
try{
rs.close();
}catch(SQLException ex){};
}}}
4.运用
QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
案例: