一些开源组织提供了数据源的独立实现:
DBCP数据库连接池
C3P0数据库连接池
Apache Tomcat内置的连接池
DBCP连接池
apache提供的连接池实现,需要导入common-dbcp.jar commons-pool.jar
import java.io.FileReader; java.sql.Connection; java.sql.ResultSet; java.sql.Statement; java.util.Properties; javax.sql.DataSource; org.apache.commons.dbcp.BasicDataSourceFactory; public class DBCPTest { static void main(String[] args) throws Exception { //导入配置文件 Properties prop=new Properties(); prop.load(new FileReader("dbcp.properties")); 获取数据源 BasicDataSourceFactory factory= 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
C3P0连接池
java.sql.Statement; com.mchange.v2.c3p0.ComboPooledDataSource; 使用C3P0 ComboPooledDataSource pool= ComboPooledDataSource(); Connection conn= 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="jdbcUrl">jdbc:MysqL:///java="user">root="password"> >