1. Tomcat连接池:
1.修改Tomcat context.xml 文
(E:\JavaTool\Tomcat\apache-tomcat-9.0.53\conf\路径)
<Resource name="jdbc/xmx"
auth="Container" type="javax.sql.DataSource" maxActive="100"
maxIdle="30" maxWait="10000" username="root" password="19990507"
driverClassName="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/321myschool?characterEncoding=utf-8">
</Resource>
maxActive=“100”----(int)可以同时从该池分配的最大活动连接数。默认值为100
maxIdle=“30”----始终应保留在池中的最大连接数
minIdle=“10”—始终应保留在池中的已建立连接的最小数目
username="root"数据库账号 password="19990507"数据库密码
BaseDao
static {
try {
//读取连接池的配置
Context context = new InitialContext();
//连接池的创建初始化
ds = (DataSource) context.lookup("java:comp/env/jdbc/xmx");
} catch (NamingException e) {
e.printStackTrace();
}
}
//通过连接池获取连接对象--Tomcat
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
资源关闭
public static void close(Connection connection, Statement statement, ResultSet set) {
try {
if (connection != null) {
connection.close();
}
if (statement != null) {
statement.close();
}
if (set != null) {
set.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
2. C3J0连接池
1将一下代码写入一个 “c3p0-config.xml”(必须为这个名字)
<?xml version='1.0' encoding='UTF-8'?>
<c3p0-config>
<!-- 默认配置 创建连接池对象时,默认是加载该配置信息-->
<default-config>
<!-- 连接数据库库的配置 -->
<property name="jdbcUrl">jdbc:mysql://localhost:3306/321myschool?characterEncoding=utf-8</property>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">19990507</property>
<!-- 连接池的参数配置 -->
<!--连接用完了自动增量3个-->
<property name="acquireIncrement">5</property>
<!--连接池中初始的连接数。-->
<property name="initialPoolSize">50</property>
<!--连接池中保留的最少连接数。-->
<property name="minPoolSize">2</property>
<!--连接池中保留的最大连接数。-->
<property name="maxPoolSize">60</property>
<!--acquireRetryDelay;两次连接中间隔1000毫秒。 -->
<property name="acquireRetryDelay">1000</property>
<!--maxIdleTime:最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。-->
<property name="maxIdleTime">60</property>
</default-config>
</c3p0-config>
2.导包
BaseDao
//c3j0 配置文件在src 下自动加载 文件文是
static ComboPooledDataSource cpds = new ComboPooledDataSource();
public static Connection getConnection() {
try {
return cpds.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}