博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【java】数据库连接池(C3P0/DBCP)的简单的应用
阅读量:2240 次
发布时间:2019-05-09

本文共 6426 字,大约阅读时间需要 21 分钟。

文章目录

一、C3P0

前言:连接池的作用详见:

1、简介:

C3P0开源免费的连接池!目前使用它的开源项目有:Spring、Hibernate等。使用第三方工具需要导入jar包,C3P0使用时还需要添加配置文件c3p0-config.xml。

2、准备:

myeclipse

jdbc相关jar
C3P0相关jar包
在这里插入图片描述

3、步骤:

3-1)导入上面的两个jar,并将jar 包build path。

3-2)设置配置文件

注意事项:

配置文件名:c3p0-config.xml(固定)
配置文件位置:src (类路径)
配置文件的内容如下:

<--默认配置方式--!>
com.mysql.jdbc.Driver
jdbc:mysql:///web_07
root
123
5
20
<--以oracle命名配置方式--!>
com.mysql.jdbc.Driver
jdbc:mysql:///web_07
root
123

添加一个测试类

在这里插入图片描述

c3p0test.java 中的代码

package it.c3p0;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import org.junit.Test;import com.mchange.v2.c3p0.ComboPooledDataSource;public class c3p0test {
@Test public void testAdduser(){
Connection conn=null; PreparedStatement pstmt=null; //1、创建连接池对象 ComboPooledDataSource datasource=new ComboPooledDataSource();//实例化后,自动加载c3p0-config.xml文件。 // 实例化后,自动加载c3p0-config.xml文件中的默认配置 //ComboPooledDataSource datasource=new ComboPooledDataSource("oracle");实例化后,自动加载c3p0-config.xml文件中的以“oracle”命名的配置 //2、连接池中获取链接 try {
conn=datasource.getConnection(); String sql="insert into user values(?,?)"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,"test1"); pstmt.setString(2, "test1pwd"); int rows=pstmt.executeUpdate(); if(rows>0){
System.out.print("添加成功");} else{
System.out.print("添加失败");} } catch (SQLException e) {
// TODO Auto-generated catch block e.printStackTrace(); } finally {
// 关闭连接 try {
if(pstmt!=null)pstmt.close(); } catch (SQLException e) {
// TODO Auto-generated catch block e.printStackTrace(); } try {
if(conn!=null)conn.close(); } catch (SQLException e) {
// TODO Auto-generated catch block e.printStackTrace(); } } } }

配置文件中的代码:

com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/mydb
root
root
5
20
com.mysql.jdbc.Driver
jdbc:mysql:///web_07
root
123

运行结果:

在这里插入图片描述

4、c3p0的工具类

仔细分析下面代码,我们大部分操作数据库时,仅仅有下面红框的部分不懂,那么我们可以使用一个工具类将其他的封装起来。

在这里插入图片描述
步骤:
新建C3P0utils工具类
在这里插入图片描述

C3P0utils.java

package it.utils;import java.sql.Connection;import java.sql.SQLException;import javax.sql.DataSource;import com.mchange.v2.c3p0.ComboPooledDataSource;public class C3P0utils {
private static ComboPooledDataSource datasource=new ComboPooledDataSource(); public static DataSource getDataSource(){
return datasource; } public static Connection getConnection(){
try {
return datasource.getConnection(); } catch (SQLException e) {
throw new RuntimeException(e); } }}

C3P0testV_2.java

package it.c3p0;import it.utils.C3P0utils;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import org.junit.Test;	public class C3P0testV_2 {
@Test public void testAdduser(){
Connection conn=null; PreparedStatement pstmt=null; //2、连接池中获取链接 try {
conn=C3P0utils.getConnection(); String sql="insert into user values(?,?)"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,"test1"); pstmt.setString(2, "test1pwd"); int rows=pstmt.executeUpdate(); if(rows>0){
System.out.print("添加成功");} else{
System.out.print("添加失败");} } catch (SQLException e) {
// TODO Auto-generated catch block e.printStackTrace(); } finally {
// 关闭连接 try {
if(pstmt!=null)pstmt.close(); } catch (SQLException e) {
// TODO Auto-generated catch block e.printStackTrace(); } try {
if(conn!=null)conn.close(); } catch (SQLException e) {
// TODO Auto-generated catch block e.printStackTrace(); } } }}

运行结果:

在这里插入图片描述

二、DBCP

1、简介:

DBCP也是一个开源的连接池!是ApacheCommon成员之一,在企业开发中也比较常见,

tomcat内置连接池。

2、准备:

myeclipse

jdbc相关jar
DBCP相关jar包
在这里插入图片描述

3、步骤:

3-1)导入上面的jar,并将jar 包build path。

3-2)设置配置文件

配置文件名称:*.properties

配置文件位置:任意,建议src(classpath/类路径)
配置文件内容:properties不能编写中文,不支持在STS中修改,必须使用记事本修改内容,否则中文注释就乱码了

#连接设置driverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/jdbcusername=rootpassword=#
initialSize=10#最大连接数量maxActive=50#
maxIdle=20#
minIdle=5#
maxWait=60000#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] #注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。connectionProperties=useUnicode=true;characterEncoding=gbk#指定由连接池所创建的连接的自动提交(auto-commit)状态。defaultAutoCommit=true#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLEdefaultTransactionIsolation=READ_UNCOMMITTED

4、工具类

package cn.itheima.jdbc.utils;import java.io.InputStream;import java.sql.Connection;import java.sql.SQLException;import java.util.Properties;import javax.sql.DataSource;import org.apache.commons.dbcp.BasicDataSourceFactory;public class DBCPUtils {
private static DataSource dataSource; static{
try {
//1.加载找properties文件输入流 InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties"); //2.加载输入流 Properties props = new Properties(); props.load(is); //3.创建数据源 dataSource = BasicDataSourceFactory.createDataSource(props); } catch (Exception e) {
throw new RuntimeException(e); } } public static DataSource getDataSource(){
return dataSource; } public static Connection getConnection(){
try {
return dataSource.getConnection(); } catch (SQLException e) {
throw new RuntimeException(e); } }}

测试类文件:

package cn.itheima.jdbc.test;import java.sql.Connection;import java.sql.PreparedStatement;import org.junit.Test;import cn.itheima.jdbc.utils.DBCPUtils;public class TestDBCP {
@Test public void testUpdateUserById(){
Connection conn = null; PreparedStatement pstmt = null; try {
conn = DBCPUtils.getConnection(); String sql ="update tbl_user set upassword=? where uid=?"; pstmt= conn.prepareStatement(sql); pstmt.setString(1, "柳岩"); pstmt.setInt(2, 20); int rows = pstmt.executeUpdate(); if(rows>0){
System.out.println("更新成功!"); }else{
System.out.println("更新失败!"); } } catch (Exception e) {
throw new RuntimeException(e); } }}

转载地址:http://yxhbb.baihongyu.com/

你可能感兴趣的文章
用 Doc2Vec 得到文档/段落/句子的向量表达
查看>>
使聊天机器人具有个性
查看>>
使聊天机器人的对话更有营养
查看>>
一个 tflearn 情感分析小例子
查看>>
attention 机制入门
查看>>
手把手用 IntelliJ IDEA 和 SBT 创建 scala 项目
查看>>
GAN 的 keras 实现
查看>>
AI 在 marketing 上的应用
查看>>
Logistic regression 为什么用 sigmoid ?
查看>>
Logistic Regression 为什么用极大似然函数
查看>>
SVM 的核函数选择和调参
查看>>
LightGBM 如何调参
查看>>
用 TensorFlow.js 在浏览器中训练神经网络
查看>>
cs230 深度学习 Lecture 2 编程作业: Logistic Regression with a Neural Network mindset
查看>>
梯度消失问题与如何选择激活函数
查看>>
为什么需要 Mini-batch 梯度下降,及 TensorFlow 应用举例
查看>>
为什么在优化算法中使用指数加权平均
查看>>
初探Java设计模式4:一文带你掌握JDK中的设计模式
查看>>
初探Java设计模式5:一文了解Spring涉及到的9种设计模式
查看>>
Java集合详解1:一文读懂ArrayList,Vector与Stack使用方法和实现原理
查看>>