1.导入jar包
导入这两个jar包
下载jar包地址:Maven Repository: Search/Browse/Explore (mvnrepository.com)
(进去网站后直接在搜索框搜索并下载即可)
2.创建编写后缀为 .xml 文件
(这里也可百度)
12 3 <default-config> 4 5 com.mysql.jdbc.Driver 6jdbc:mysql://localhost:3306/test02?serverTimezone=Asia/Shanghai 7root 8root 9 10 11 125 13 1410 15 163000 17 default-config> 18 19 20 21 22 23 24 25 26 27 28 29 30 31
3.创建utils包(获取connection,释放连接资源)
1 public class JdbcUtils_c3p0 {
2
3 private static DataSource dataSource;
4 static {
5 try {
6
7 //创建数据源 工厂模式 --》创建
8 dataSource = new ComboPooledDataSource(); //只需要new 即可使用
9
10
11 } catch (Exception e) {
12 e.printStackTrace();
13 }
14 }
15
16 //获取连接
17 public static Connection getConnection() throws Exception{
18 return dataSource.getConnection(); //包里面自带getConnection,不需要手写
19
20 }
21 //释放链接资源
22 public static void release(Connection connection, Statement statement, ResultSet resultSet){
23 try {
24 if (resultSet != null) {
25 resultSet.close();
26 }
27 if (statement != null) {
28 statement.close();
29 }
30 if (connection != null) {
31 connection.close();
32 }
33 }catch (Exception e){
34 e.printStackTrace();
35 }
36 }
37 }
4.测试
1 Connection connection = null;
2 PreparedStatement ps = null;
3 ResultSet resultSet =null;
4 //1.获取数据库连接
5 try {
6 connection = JdbcUtils_c3p0.getConnection();
7 String sql = "insert into student (name,sex,birthday,tall) values (?,?,?,?)";
8 ps = connection.prepareStatement(sql); //预编译sql 先写sql,然后不执行
9 //手动为参数赋值
10 ps.setString(1, "嗷嗷嗷");
11 ps.setString(2, "男");
12 ps.setString(3, "2002.1.8");
13 ps.setDouble(4, 1.75);
14 //执行
15 ps.executeUpdate();
16
17 } catch (Exception e) {
18 e.printStackTrace();
19 } finally {
20 JdbcUtils.release(connection, ps, resultSet);
21 }
Original: https://www.cnblogs.com/qiaoyuqi/p/15780911.html
Author: 咸鱼乔
Title: c3p0
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/572186/
转载文章受原作者版权保护。转载请注明原作者出处!