使用c3p0
導入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文件加入數(shù)據(jù)源配置
<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 {
//創(chuàng)建上下文
Context context=new InitialContext();
//獲取數(shù)據(jù)源
ComboPooledDataSource comboPooledDataSource= (ComboPooledDataSource) context.lookup
("java:comp/env/jdbc/myDB");
//獲取數(shù)據(jù)庫連接
Connection connection=comboPooledDataSource.getConnection();
if(!connection.isClosed()){
System.out.println("已經連接成功");
}
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
使用druid
導入jar包
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
在tomcat的context.xml文件加入數(shù)據(jù)源配置
<Resource
name="jdbc/MysqlDataSource"
factory="com.alibaba.druid.pool.DruidDataSourceFactory"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/yl?characterEncoding=utf8&serverTimezone=GMT%2B8"
username="root"
password="123456"
maxActive="50"
maxWait="10000"
removeabandoned="true"
removeabandonedtimeout="60"
logabandoned="false"
filters="stat"/>
獲取連接
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//獲取上下文對象
Context context=new InitialContext();
//獲取數(shù)據(jù)源
DataSource ds= (DataSource) context.lookup("java:comp/env/jdbc/MysqlDataSource");
//獲取Connection對象
Connection connection=ds.getConnection();
if(!connection.isClosed()){
System.out.println("連接成功");
}
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。