Java 連線池(使用DBCP與C3P0)
阿新 • • 發佈:2018-11-04
DBCP
需要下載common-dbcp.jar和common-pool.jar。
下載網址(下載xxx-bin.zip即可):
http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi
http://commons.apache.org/proper/commons-pool/download_pool.cgi
http://commons.apache.org/proper/commons-logging/download_logging.cgi
下載的時候,注意DBCP的版本與JDK版本的搭配。下載的檔案中的jar包會攜帶版本,可以將版本號刪掉。
可以將下載的jar包放到我們的專案根目錄,然後執行下面的命令解壓。
$ ls com commons-dbcp2-2.5.0-bin.zip commons-logging-1.2-bin.zip commons-pool2-2.6.0-bin.zip Test.java $ unzip -q commons-dbcp2-2.5.0-bin.zip $ unzip -q commons-pool2-2.6.0-bin.zip $ unzip -q commons-logging-1.2-bin.zip $ cp commons-dbcp2-2.5.0/commons-dbcp2-2.5.0.jar ./ $ cp commons-pool2-2.6.0/commons-pool2-2.6.0.jar ./ $ cp commons-logging-1.2/commons-logging-1.2.jar ./ $ jar xf commons-logging-1.2.jar $ jar xf commons-pool2-2.6.0.jar $ jar xf commons-dbcp2-2.5.0.jar
測試DBCP
package demo; import java.sql.*; import org.apache.commons.dbcp2.*; import org.apache.commons.pool2.*; import org.apache.commons.logging.*; public class Test { public static void main(String[] args) throws Exception{ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUsername("root"); dataSource.setPassword("root"); dataSource.setInitialSize(5); dataSource.setMinIdle(2); // dataSource.setMaxActive(10); Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); stmt.executeUpdate("update stu set age = 30 where id < 4"); conn.close(); } }