#|数据库连接池DBCP(代码连接)

DBCP普通连接连接方式

package com.java.dbcp; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.commons.dbcp.BasicDataSource; import com.java.jdbc.util.JDBCUtil; public class DBCPDemo { public void testDBCP01() {Connection connection = null; PreparedStatement ps = null; try { //1、构建数据源对象 BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost/php?useSSL=false"); dataSource.setUsername("root"); dataSource.setPassword("123456"); //2、得到连接对象 connection = dataSource.getConnection(); String sql = "insert into stus values(6,?,?)"; ps = connection.prepareStatement(sql); ps.setString(1, "ling"); ps.setString(2, "666666"); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(connection, ps); } } public static void main(String[] args) { DBCPDemo dbcp = new DBCPDemo(); dbcp.testDBCP01(); } }

DBCP连接(读取配置文件)
package com.java.dbcp; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; import com.java.jdbc.util.JDBCUtil; public class DBCPDemo02 { public void dbcpdemo() {Connection connection = null; PreparedStatement ps = null; try {BasicDataSourceFactory factory = new BasicDataSourceFactory(); Properties properties = new Properties(); InputStream iStream = new FileInputStream("src/dbcpconfig.properties"); properties.load(iStream); DataSource dataSource = factory.createDataSource(properties); //2、得到连接对象 connection = dataSource.getConnection(); String sql = "insert into stus values(7,?,?)"; ps = connection.prepareStatement(sql); ps.setString(1, "wu"); ps.setString(2, "123456789"); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally { JDBCUtil.release(connection, ps); } } public static void main(String[] args) { DBCPDemo02 demo = new DBCPDemo02(); demo.dbcpdemo(); } }

dbcpconfig.properties文件
#连接设置 driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost/php?useSSL=false username=root password=abc123456# initialSize=10#最大连接数量 maxActive=50# maxIdle=20# minIdle=5# maxWait=60000#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property; ] #注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。 connectionProperties=useUnicode=true; characterEncoding=gbk#指定由连接池所创建的连接的自动提交(auto-commit)状态。 defaultAutoCommit=true#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。 #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE defaultTransactionIsolation=READ_UNCOMMITTED

【#|数据库连接池DBCP(代码连接)】效果图
#|数据库连接池DBCP(代码连接)
文章图片

正在尝试写博客,把会的分享给你们,如有写的不好的地方,希望指点一下,谢谢!

    推荐阅读