导入c3p0jar包
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
在tomcat的context.xml文件加入数据源配置
<Resource
auth="Container"
description="DB Connection"
driverClass="com.mysql.jdbc.Driver"
maxPoolSize="100" minPoolSize="2"
acquireIncrement="2"
name="jdbc/myDB"
user="root"
password="123456"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:mysql://localhost:3306/attendance_system?characterEncoding=utf8&serverTimezone=GMT%2B8" />
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//创建上下文
Context context=new InitialContext();
//获取数据源
ComboPooledDataSource comboPooledDataSource= (ComboPooledDataSource) context.lookup
("java:comp/env/jdbc/myDB");
//获取数据库连接
Connection connection=comboPooledDataSource.getConnection();
if(!connection.isClosed()){
System.out.println("已经连接成功");
}
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
原文:https://www.cnblogs.com/Y-wee/p/13679904.html