查看“JDBCUtils中使用C3P0数据库连接池获取连接”的源代码
←
JDBCUtils中使用C3P0数据库连接池获取连接
跳到导航
跳到搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看和复制此页面的源代码。
https://www.bilibili.com/video/BV1eJ411c7rf?p=48 === 新的 JDBCUtils === <syntaxhighlight lang="java"> package io.github.jihch.betterutil; import com.mchange.v2.c3p0.ComboPooledDataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class JDBCUtils { private static ComboPooledDataSource cpds = new ComboPooledDataSource("helloc3p0"); /** * 使用C3P0连接池技术 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { Connection conn = cpds.getConnection(); return conn; } /** * 关闭连接和 Statement 的操作 * @param conn * @param ps */ public static void closeResource(Connection conn, Statement ps){ try { if (ps != null) { ps.close(); } } catch (SQLException e) { throw new RuntimeException(e); } if (conn != null){ try { conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } } </syntaxhighlight> === 测试新的 JDBCUtils === <syntaxhighlight lang="java"> package io.github.jihch.betterutil; import io.github.jihch.bean.Customer; import io.github.jihch.betterdao.CustomerDAOImpl; import org.junit.Test; import java.sql.Connection; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.*; public class JDBCUtilsTest { private CustomerDAOImpl dao = new CustomerDAOImpl(); @Test public void getConnection1() { Connection con = null; try { con = JDBCUtils.getConnection(); Customer customer = dao.getCustomerById(con, 4); System.out.println(customer); } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.closeResource(con, null); } } /** * 每次 connnection 的 hashcode 都不同,怎么判断 connnection 被重用了? */ @Test public void getConnection2() { Connection con = null; Set<Integer> set = new HashSet<>(); for (int i = 0; i < 100; i++) { try { con = JDBCUtils.getConnection(); set.add(con.hashCode()); } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.closeResource(con, null); } } set.forEach(System.out::println); } } </syntaxhighlight>
返回至
JDBCUtils中使用C3P0数据库连接池获取连接
。
导航菜单
个人工具
登录
名字空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
Spring Boot 2 零基础入门
Spring Cloud
Spring Boot
设计模式之禅
VUE
Vuex
Maven
算法
技能树
Wireshark
IntelliJ IDEA
ElasticSearch
VirtualBox
软考
正则表达式
程序员精讲
软件设计师精讲
初级程序员 历年真题
C
SQL
Java
FFmpeg
Redis
Kafka
MySQL
Spring
Docker
JMeter
Apache
Linux
Windows
Git
ZooKeeper
设计模式
Python
MyBatis
软件
数学
PHP
IntelliJ IDEA
CS基础知识
网络
项目
未分类
MediaWiki
镜像
问题
健身
国债
英语
烹饪
常见术语
MediaWiki帮助
工具
链入页面
相关更改
特殊页面
页面信息