使用数据库连接池方式与普通方式对比
package com.micro.profession.jdbc.practice;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.dbcp2.BasicDataSource;
//继承Thread父类
public class DBPoolDbcpImpl extends Thread{
public static BasicDataSource ds = null;
static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/cloud_study";
static final String USER_NAME = "root";
static final String PASSWORD = "123456";
public static void dbpoolInit() {
ds = new BasicDataSource();
ds.setUrl(DB_URL);
ds.setDriverClassName(DRIVER_NAME);
ds.setUsername(USER_NAME);
ds.setPassword(PASSWORD);
ds.setMaxTotal(2);
}
//数据库连接池方式,ds
public void dbPoolTest() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from user");
while (rs.next()) {
System.out.println(rs.getString("userName"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
if (stmt != null)
stmt.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
// ignore
}
}
}
//普通方式连接数据库
public void jdbcTest() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName(DRIVER_NAME);
conn = DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from user");
while (rs.next()) {
System.out.println(rs.getString("userName"));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e1) {
// ignore
} finally {
try {
if (conn != null)
conn.close();
if (stmt != null)
stmt.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
// ignore
}
}
}
//重写父类的run()方法。在run()方法中加入具体的任务代码或处理逻辑。
public void run() {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 10000) {
// jdbcTest();
dbPoolTest();
}
}
public static void main(String[] args) {
dbpoolInit();
// 开启10个线程Thread
// 调用start方法,线程t启动,隐含的调用run()方法。
for(int i =0 ;i<10 ;i++){
new DBPoolDbcpImpl().start();
}
}
}
DBCP与JDBC驱动,maven引用
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
程序运行之后,在mysql中使用show processlist;查看线程情况。
1.使用普通方式jdbcTest();有10个线程
2.使用连接池dbPoolTest();只有设置的2个线程