步骤一:导入所需要的jar包(略)如图:
步骤二:编写properties配置文件
具体参考内容如下:
url=jdbc:mysql://localhost:3306/db_wwq username=root password=root driverClassName=com.mysql.cj.jdbc.Driver initialSize=10 maxActive=20 maxWait=1000
步骤三:编写JdbcUtils工具类java文件
public class JdbcUtils {
private static DataSource dataSource;
private static ThreadLocal threadLocal;
static {
try {
//加载连接池配置文件,创建DataSource
Properties properties = new Properties();
properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"));
dataSource = DruidDataSourceFactory.createDataSource(properties);
//初始化ThreadLocal对象
threadLocal = new ThreadLocal<>();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取数据库连接池
public static Connection getConnection(){
//从threadlocal获取连接
Connection connection = threadLocal.get();
if (connection==null){
try {
connection = dataSource.getConnection();
threadLocal.set(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
//释放资源
public static void closeResource(){
Connection connection = threadLocal.get();
if (connection != null){
try {
connection.close();
threadLocal.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
步骤四:编写TestUtils测试类java文件
public class TestUtils {
public static void main(String[] args) {
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
Connection connection = JdbcUtils.getConnection();
String sql = "select * from stu";
preparedStatement = connection.prepareStatement(sql);
rs = preparedStatement.executeQuery();
while (rs.next()){
System.out.println(rs.getString("sname"));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
rs.close();
preparedStatement.close();
JdbcUtils.closeResource();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
步骤五:运行代码查看运行结果:
五月 13, 2022 3:10:24 下午 com.alibaba.druid.pool.DruidDataSource info
信息: {dataSource-1} inited
liuYi
chenEr
zhangSan
liSi
wangWu
zhaoLiu
sunQi
zhouBa
wuJiu
zhengShi
xxx
diedie
Process finished with exit code 0



