数据库连接池

xiaoxiao2021-02-28  56

Connection对象的创建和销毁时比较消耗系统资源的,为了减少Connection对象的创建和销毁,需要数据库连接池。

原理:在连接池中投放一定量的连接对象,连接对象使用后不会进行销毁,而是直接放入连接池,闲置的连接对象可以被反复使用。

这里要用到C3P0。

拷贝c3p0、mchange两个jar包,并添加到项目中。

数据库工具类:

public class JDBCUtil { //创建连接池对象 private static ComboPooledDataSource cpds = new ComboPooledDataSource(); /** * 返回连接池中的连接对象 * @return */ public static Connection getConnection(){ try { return cpds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return null; }

}

在src下添加配置文件c3p0-config.xml(文件名是其他的)

<c3p0-config> <default-config> <property  name="jdbcUrl"> jdbc:mysql://localhost:3306/cloudnotes</property> <property  name="driverClass">com.mysql.jdbc.Driver</property> <property  name="user">root</property> <property  name="password">199616</property> <property  name="acquireIncrement">3</property> <property  name="initialPoolSize">10</property> <property  name="minPoolSize">2</property> <property  name="maxPoolSize">10</property> </default-config> </c3p0-config>

通过JDBCUtil.getConnection()获得连接对象

转载请注明原文地址: https://www.6miu.com/read-46666.html

最新回复(0)