文章目录

  • 作者简介
  • 引言
  • 导航
  • 热门专栏推荐
  • 一、下载驱动并加入项目中
  • 二、编写配置文件
  • 三、编写工具类
  • 四、编写测试类
  • 五、测试运行
  • 小结
  • 导航
  • 热门专栏推荐

作者简介

作者名:编程界明世隐
简介:CSDN博客专家,从事软件开发多年,精通Java、JavaScript,博主也是从零开始一步步把学习成长、深知学习和积累的重要性,喜欢跟广大ADC一起打野升级,欢迎您关注,期待与您一起学习、成长、起飞!

引言

我本来是一直用eclipse和myeclipse的老程序员了,很多我的粉丝小伙伴都说他们要用idea,问我怎么不用idea,其实明哥觉得用啥开发工具都不是重点,重点是要跟着明哥多学Java知识、多练习,但是作为一个宠粉的人,我怎么能拒绝粉丝的要求呢,于是我偷偷的去学习了一波(拿来吧你),然后就写了这个系列,希望小伙伴们能有所收获,明哥会努力更新的。

导航

✪ idea从零到精通目录索引
◄上一篇【11】用JDBC连接Mysql数据库
►下一篇【13】把eclipse开发的web项目导入到IDEA中

热门专栏推荐

【1】Java小游戏(俄罗斯方块、飞机大战、植物大战僵尸等)
【2】JavaWeb项目实战(图书管理、在线考试、宿舍管理等)
【3】JavaScript精彩实例(飞机大战、贪吃蛇、验证码等)
【4】Java小白入门200例
【5】从零学Java、趣学Java
【6】Idea从零到精通

一、下载驱动并加入项目中

  1. 网上下载Mysql jar包和c3p0的jar包(总共有3个),需要jar包的可以到公众号“编程界明世隐”,回复:“mysql驱动”,下载这几个jar包
    打开项目,依次打开目录,web–WEB-INF–lib 加入这几个驱动jar包。
    我的jar包名称如下:

mchange-commons-java-0.2.3.4.jar
mysql-connector-java-5.0.8-bin.jar
c3p0-0.9.2.1.jar

  1. 引入jar包到项目中

    File – Project Structure… – Libraies


点击“加号” – Java

选择好你项目中lib下的驱动jar包,点击OK

加入后效果图如下,点击OK

  1. c3p0 jar包引入方式和mysql一样。

    还有mchange-commons-java jar包

二、编写配置文件

在src下放入xml配置:c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config><!--C3P0的缺省(默认)配置,如果在代码中“ComboPooledDataSource ds = new ComboPooledDataSource();”这样写就表示使用的是C3P0的缺省(默认)配置信息来创建数据源--><default-config><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost:3306/library?characterEncoding=utf8</property><property name="user">root</property><property name="password">root</property><property name="acquireIncrement">5</property><property name="initialPoolSize">10</property><property name="minPoolSize">5</property><property name="maxPoolSize">20</property></default-config><!--C3P0的命名配置,如果在代码中“ComboPooledDataSource ds = new ComboPooledDataSource("MySQL");”这样写就表示使用的是name是MySQL的配置信息来创建数据源--><named-config name="MySQL"><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost:3306/library?characterEncoding=utf8</property><property name="user">root</property><property name="password">root</property><property name="acquireIncrement">5</property><property name="initialPoolSize">10</property><property name="minPoolSize">5</property><property name="maxPoolSize">20</property></named-config></c3p0-config>

三、编写工具类

import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import com.mchange.v2.c3p0.ComboPooledDataSource;public class C3P0_Utils {private static ComboPooledDataSource dataSource = null;//在静态代码块中创建数据库连接池static{try{dataSource = new ComboPooledDataSource("MySQL");//使用C3P0的命名配置来创建数据源System.out.println(dataSource);}catch (Exception e) {throw new ExceptionInInitializerError(e);}}public static Connection getConnection() throws SQLException{//从数据源中获取数据库连接return dataSource.getConnection();}// 释放资源public static void release(Connection conn,Statement st,ResultSet rs){if(rs!=null){try{//关闭存储查询结果的ResultSet对象rs.close();}catch (Exception e) {e.printStackTrace();}rs = null;}if(st!=null){try{//关闭负责执行SQL命令的Statement对象st.close();}catch (Exception e) {e.printStackTrace();}}if(conn!=null){try{//将Connection连接对象还给数据库连接池conn.close();}catch (Exception e) {e.printStackTrace();}}}}

四、编写测试类

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;public class DataSourceTest {public void c3p0DataSourceTest() {Connection conn = null;Statement st = null;ResultSet rs = null;try {//获取数据库连接conn = C3P0_Utils.getConnection();String sql = "select * from user";     // 查询数据的sql语句st = (Statement) conn.createStatement();    //创建用于执行静态sql语句的Statement对象,st属局部变量rs = st.executeQuery(sql);    //执行sql查询语句,返回查询数据的结果集System.out.println("最后的查询结果为:");while (rs.next()) { // 判断是否还有下一个数据// 根据字段名获取相应的值String name = rs.getString("name");String no = rs.getString("no");//输出查到的记录的各个字段的值System.out.println("名字:" + name + ",账号 " + no);}} catch (Exception e) {e.printStackTrace();} finally {//释放资源C3P0_Utils.release(conn, st, rs);}}public static void main(String[] args) {new DataSourceTest().c3p0DataSourceTest();}
}

五、测试运行

可以在最后几行的位置看到查询结果。

MLog clients using log4j logging.
Initializing c3p0-0.9.2.1 [built 20-March-2013 11:16:28 +0000; debug? true; trace: 10]
MBean: com.mchange.v2.c3p0:type=PooledDataSource,identityToken=1okythyak1w154khck75wa|bebdb06,name=1okythyak1w154khck75wa|bebdb06 registered.
MBean: com.mchange.v2.c3p0:type=PooledDataSource,identityToken=1okythyak1w154khck75wa|bebdb06,name=1okythyak1w154khck75wa|bebdb06 unregistered, in order to be reregistered after update.
MBean: com.mchange.v2.c3p0:type=PooledDataSource,identityToken=1okythyak1w154khck75wa|bebdb06,name=1okythyak1w154khck75wa|bebdb06 registered.
MBean: com.mchange.v2.c3p0:type=PooledDataSource,identityToken=1okythyak1w154khck75wa|bebdb06,name=1okythyak1w154khck75wa|bebdb06 unregistered, in order to be reregistered after update.
MBean: com.mchange.v2.c3p0:type=PooledDataSource,identityToken=1okythyak1w154khck75wa|bebdb06,name=MySQL registered.
com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 5, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> MySQL, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1okythyak1w154khck75wa|bebdb06, idleConnectionTestPeriod -> 0, initialPoolSize -> 10, jdbcUrl -> jdbc:mysql://localhost:3306/library?characterEncoding=utf8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 5, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 5, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> MySQL, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1okythyak1w154khck75wa|bebdb06, idleConnectionTestPeriod -> 0, initialPoolSize -> 10, jdbcUrl -> jdbc:mysql://localhost:3306/library?characterEncoding=utf8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 5, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
incremented pending_acquires: 1
Starting acquisition series. Incremented pending_acquires [1],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@5fe5c6f
incremented pending_acquires: 2
Starting acquisition series. Incremented pending_acquires [2],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@6979e8cb
incremented pending_acquires: 3
Starting acquisition series. Incremented pending_acquires [3],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@763d9750
incremented pending_acquires: 4
Starting acquisition series. Incremented pending_acquires [4],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@5c0369c4
incremented pending_acquires: 5
Starting acquisition series. Incremented pending_acquires [5],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@2be94b0f
incremented pending_acquires: 6
Starting acquisition series. Incremented pending_acquires [6],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@d70c109
incremented pending_acquires: 7
Starting acquisition series. Incremented pending_acquires [7],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@17ed40e0
incremented pending_acquires: 8
Starting acquisition series. Incremented pending_acquires [8],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@50675690
incremented pending_acquires: 9
Starting acquisition series. Incremented pending_acquires [9],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@31b7dea0
incremented pending_acquires: 10
Starting acquisition series. Incremented pending_acquires [10],  attempts_remaining: 30
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@3ac42916
com.mchange.v2.resourcepool.BasicResourcePool@47d384ee config: [start -> 10; min -> 5; max -> 20; inc -> 5; num_acq_attempts -> 30; acq_attempt_delay -> 1000; check_idle_resources_delay -> 0; mox_resource_age -> 0; max_idle_time -> 0; excess_max_idle_time -> 0; destroy_unreturned_resc_time -> 0; expiration_enforcement_delay -> 0; break_on_acquisition_failure -> false; debug_store_checkout_exceptions -> false]
Created new pool for auth, username (masked): 'ro******'.
acquire test -- pool size: 0; target_pool_size: 10; desired target? 1
awaitAvailable(): [unknown]
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 0, unused: 0, excluded: 0]
com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager@3eba6356.acquireResource() returning.
com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager@3eba6356.acquireResource() returning.
com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager@3eba6356.acquireResource() returning.
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 1, unused: 1, excluded: 0]
decremented pending_acquires: 9
Acquisition series terminated successfully. Decremented pending_acquires [9],  attempts_remaining: 30
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 2, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@1886e3b)
decremented pending_acquires: 8
Acquisition series terminated successfully. Decremented pending_acquires [8],  attempts_remaining: 30
com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager@3eba6356.acquireResource() returning.
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 3, unused: 3, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@1886e3b)
decremented pending_acquires: 7
Acquisition series terminated successfully. Decremented pending_acquires [7],  attempts_remaining: 30
com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager@3eba6356.acquireResource() returning.
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 4, unused: 4, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@1886e3b)
decremented pending_acquires: 6
Acquisition series terminated successfully. Decremented pending_acquires [6],  attempts_remaining: 30
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 4, unused: 3, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@1886e3b)
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 5, unused: 4, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@1886e3b)
decremented pending_acquires: 5
Acquisition series terminated successfully. Decremented pending_acquires [5],  attempts_remaining: 30
com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager@3eba6356.acquireResource() returning.
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 6, unused: 5, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@1886e3b)
decremented pending_acquires: 4
Acquisition series terminated successfully. Decremented pending_acquires [4],  attempts_remaining: 30
com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager@3eba6356.acquireResource() returning.
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 7, unused: 6, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@1886e3b)
decremented pending_acquires: 3
Acquisition series terminated successfully. Decremented pending_acquires [3],  attempts_remaining: 30
com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager@3eba6356.acquireResource() returning.
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 8, unused: 7, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@1886e3b)
decremented pending_acquires: 2
Acquisition series terminated successfully. Decremented pending_acquires [2],  attempts_remaining: 30
最后的查询结果为:
名字:超级管理,账号 sa
名字:student001,账号 001
名字:student002,账号 002
名字:管理员1,账号 admin
名字:管理员002,账号 admin2
com.mchange.v2.async.ThreadPoolAsynchronousRunner@2471cca7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$1RefurbishCheckinResourceTask@73035e27
trace com.mchange.v2.resourcepool.BasicResourcePool@47d384ee [managed: 8, unused: 7, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@1886e3b)

小结

这节总结了“ 用C3P0连接Mysql数据库 ”,希望能对大家有所帮助,请各位小伙伴帮忙 【点赞】+【收藏】+ 【评论区打卡】, 如果有兴趣跟小明哥一起学习Java的,【关注一波】不迷路哦。

评论区打卡一波让我知道你,明哥会持续关注你的学习进度哦!

导航

✪ idea从零到精通目录索引
◄上一篇【11】用JDBC连接Mysql数据库
►下一篇【13】把eclipse开发的web项目导入到IDEA中

热门专栏推荐

【1】Java小游戏(俄罗斯方块、飞机大战、植物大战僵尸等)
【2】JavaWeb项目实战(图书管理、在线考试、宿舍管理等)
【3】JavaScript精彩实例(飞机大战、贪吃蛇、验证码等)
【4】Java小白入门200例
【5】从零学Java、趣学Java
【6】Idea从零到精通

IDEA从零到精通(12)之用C3P0连接Mysql数据库相关推荐

  1. MySQL笔记12:C语言访问MYSQL数据库的完整的代码例子

    C语言访问MYSQL数据库的完整的代码例子 1.手写安装带mysql sdk 的mysql 2.新建控制台项目,项目属性中把 C:\Program Files\MySQL\MySQL Server 5 ...

  2. MySQL从入门到精通50讲(一)-MySQL数据库操作创建数据库及删除数据库

    前言 声明:以下是博主精心整理的机器学习和AI系列文章,博主后续会不断更新该领域的知识: 人工智能AI实战系列代码全解析 手把手教你ML机器学习算法源码全解析 有需要的小伙伴赶紧订阅吧. MySQL ...

  3. mysql date 24小时制_SpringBoor连接mysql数据库取数据库中时间格式是12小时制的时间,如何显示成24小时制...

    设置spring配置文件: 1.spring.datasource.url=jdbc:mysql://10.35.105.25:3306/database?characterEncoding=utf- ...

  4. 12日直播预告丨MySQL故障诊断常用方法手册

    经典知识库:MySQL故障诊断常用方法手册 -8月12日20:00 在MySQL数据库运维中,你是否还在被故障分析诊断弄得焦头烂额?为问题处理不掉而愁眉苦脸?别着急,本次我们邀请到有 多年MySQL运 ...

  5. mysql数据库建站教程视频_Mysql数据库零基础到精通视频教程(共6天)

    php教程 当前位置:主页 > php教程 > Mysql数据库零基础到精通视频教程(共6天) Mysql数据库零基础到精通视频教程(共6天) 教程大小:886MB   发布时间:2016 ...

  6. idea从零到精通02之idea基础设置

    作者简介 作者名:编程界明世隐 简介:CSDN博客专家,从事软件开发多年,精通Java.JavaScript,博主也是从零开始一步步把学习成长.深知学习和积累的重要性,喜欢跟广大ADC一起打野升级,欢 ...

  7. mysql php教程视频教程下载地址_最全138节Mysql数据库+PHP零基础到精通,视频教程下载...

    课程名称 最全138节Mysql数据库+PHP零基础到精通,视频教程下载 课程目录 01数据库课程介绍 02数据库(基础知识) 03数据库(关系型数据库) 04数据库(关系型数据库关键字说明) 05数 ...

  8. mysql视频教程siki_siki老师MySQL数据库从零到精通,资源教程下载

    课程名称 siki老师MySQL数据库从零到精通,资源教程下载 课程目录 01-什么是数据库 学习方法介绍 02-各种数据库的比较和关系型数据库的介绍 03-服务器端运行通信原理图 04-游戏服务器端 ...

  9. 数据分析从零到精通第三课 python自动化和BI数据可视化实战

    05 效率提升:如何通过邮件报表释放人力 本课时主要分享从零搭建数据邮件日报系统的方法,从而满足业务方的定期数据需求.希望通过本课时的介绍,你可以立刻在自己机器上实践定时邮件发送的任务. 邮件日报的业 ...

最新文章

  1. mysql 事务_MySQL事务
  2. excel 按数据拆分 xlam_利用EXCEL提升效率之五分钟缩短至五秒批量合并EXCEL批量转换PDF批量上传报关单随附单据___EXCELVBA...
  3. Linux centosVMware Apache 配置防盗链、访问控制Directory、访问控制FilesMatch
  4. Spring整合Mybatis之注解方式,(注解整合Junit)
  5. centos7.2 安装poco
  6. 计算机操作系统(4):操作系统的重要功能
  7. oauth2.0 php简化模式,OAuth2.0学习(1-5)授权方式2-简化模式(implicit grant type)
  8. ID Tech 5 中 Megatexturequot;针对地形的D3D9 基本实现原理
  9. ubuntu下配置php环境
  10. 说说如何在 Spring 框架中使用 SpEL 表达式
  11. [笔记]3.软件代码中的BUG问题的一些记录
  12. Multisim单结晶体管触发电路仿真
  13. 菜鸟日记(yzy):集成Ucrop裁剪图片架构,并创建管理类使用
  14. 【OJ每日一练】1049 - 矩阵对角线元素之和 v1.0
  15. 杜比dss200服务器重装,杜比数字影院处理器 DSS200 (Dolby Screen Server DSS200)
  16. 计算机组成原理——编译器、汇编器和链接器的基本概念
  17. 基于Matlab 实现螺旋线 轨迹曲线绘制
  18. 让DedeCMS的栏目页标题显示页码数
  19. 浅谈均值、方差、标准差、协方差的概念及意义
  20. 《明解C语言入门篇》 基础知识点汇总

热门文章

  1. 数字图像处理 实验指导书
  2. 无MMU实现非法内存访问安全的一种方法
  3. 引用网络jQuery地址
  4. 计算机基础应用试题——第二卷
  5. 线程与进程、Android多线程编程
  6. 技嘉 gigabyte b75m d3v 主板 定时开机无效问题解决
  7. 汤晓丹的第四版计算机操作系统--第九章总结概述
  8. 【随笔】Inconsolata字体的下载安装及在VS2017中使用该字体
  9. 动易BizIdea和SpaceBuilder实现单点登录
  10. 新发现一个免费虚拟主机平台感觉还不错