标签:
一些开源组织提供了数据源的独立实现:
DBCP数据库连接池
C3P0数据库连接池
Apache Tomcat内置的连接池
DBCP连接池
apache提供的连接池实现,需要导入common-dbcp.jar commons-pool.jar
import java.io.FileReader; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; public class DBCPTest { public static void main(String[] args) throws Exception { //导入配置文件 Properties prop=new Properties(); prop.load(new FileReader("dbcp.properties")); //获取数据源 BasicDataSourceFactory factory=new BasicDataSourceFactory(); DataSource pool=factory.createDataSource(prop); Connection conn=pool.getConnection(); //获取传输器对象 Statement statement=conn.createStatement(); //获取结果集对象 ResultSet resultSet=statement.executeQuery("select * from user"); //遍历 while(resultSet.next()){ String username=resultSet.getString("username"); System.out.println(username); } //关闭资源 resultSet.close(); statement.close(); conn.close(); } }
在项目目录下新建dacp.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///java
username=root
password=root
C3P0连接池
import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DBCPTest { public static void main(String[] args) throws Exception { //使用C3P0 ComboPooledDataSource pool=new ComboPooledDataSource(); Connection conn=pool.getConnection(); //获取传输器对象 Statement statement=conn.createStatement(); //获取结果集对象 ResultSet resultSet=statement.executeQuery("select * from user"); //遍历 while(resultSet.next()){ String username=resultSet.getString("username"); System.out.println(username); } //关闭资源 resultSet.close(); statement.close(); conn.close(); } }
C3P0需要在类加载目录下新建c3p0-config.xml
<?xml version="1.0" encoding="utf-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///java</property> <property name="user">root</property> <property name="password">root</property> </default-config> </c3p0-config>
标签:
原文地址:http://www.cnblogs.com/taoshihan/p/5655433.html