配置文件
<?xml version="1.0" encoding="utf-8"?>
<c3p0-config><named-config name="sqlserver">
<property name="driverClass">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="jdbcUrl">jdbc:sqlserver://localhost:1434; DatabaseName=db_news2</property>
<property name="user">sa</property>
<property name="password">sa</property>
<property name="acquireIncrement">10</property>
<property name="initialPoolSize">5</property>
<property name="maxIdleTime">300</property>
<property name="maxPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxStatements">10</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
测试文件:
package database;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource ;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class SQLDB {
private static DataSource ds ;
static {
ds = new ComboPooledDataSource( "sqlserver" ); // 配置文件中设置的内容不用写其他的是因为它可以自动查找 classloader 下的 c3p0-config.xml 文件(要注意的是文件的名称必须是 c3p0-config.xml )如果文件的名称不是这个,将出现错误。
}
// 获取与指定数据的连接
public static DataSource getSource(){
return ds ;
}
// 获得与指定数据库的连接
public static Connection getConnection() throws SQLException {
// 从连接池返回一个连接
return ds .getConnection();
}
// 释放资源
public static void release(ResultSet rs,Statement stmt,Connection conn) {
if (rs!= null ){
try {
rs.close();
} catch (SQLException e){
e.printStackTrace();
}
rs = null ;
}
if (stmt!= null ){
try {
stmt.close();
} catch (SQLException e){
e.printStackTrace();
}
stmt= null ;
}
if (conn!= null ){
try {
conn.close();
} catch (SQLException e){
e.printStackTrace();
}
conn = null ;
}
}
@Test
public void testnews()
{
SQLDB sqldb = new SQLDB();
Statement stm;
try {
stm = sqldb.getConnection().createStatement();
ResultSet rs = stm.executeQuery("select * from newsusr");
if(rs.next())
{
System.out.println("执行结果");
System.out.println(rs.getString("userName"));
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}