一些開源組織提供了數據源的獨立實現:
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>