JavaWeb之DButils(三)使用C3P0实现数据库的连接池

一、首先准备c3p0-config.xml文件,这里我放在src下面




  
    com.mysql.jdbc.Driver
	jdbc:mysql:///mybase
	root
	root
	5
	20
  
  
   
    com.mysql.jdbc.Driver
	jdbc:mysql:///mybase
	root
	root
  
  


二、创建C3P0Utils工具类

package com.shuhuadream.jdbc.utils01;

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("oracle");
	
	public static DataSource getDataSource(){
		return dataSource;
	}
	
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}

三、进行测试

package com.shuhaudream.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


import org.junit.Test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.shuhuadream.jdbc.utils01.C3P0Utils;
import com.shuhuadream.jdbc.utils01.JDBCUtils_V3;

public class TestC3P0 {
	
	@Test
	public void testAddUser(){
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		try {
			//2.从池子中获取连接
			conn = C3P0Utils.getConnection();
			String sql = "INSERT INTO sort (sname,sprice,sdesc)VALUES(?,?,?)";
			//获取执行sql语句对象
			//必须在自定义的connection中重写prepareStatement(sql)方法
			pstmt = conn.prepareStatement(sql);
			//设置参数
			pstmt.setString(1, "学习用品3");
			pstmt.setString(2, "3333");
			pstmt.setString(3, "秋季开学特大优惠");
			//执行插入操作
			int rows = pstmt.executeUpdate();
			if(rows>0){
				System.out.println("数据插入成功!");
			}else{
				System.out.println("数据添加失败!");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtils_V3.release(conn, pstmt, null);
		}
	}
	
}


四、测试结果,数据插入成功

JavaWeb之DButils(三)使用C3P0实现数据库的连接池_第1张图片

JavaWeb之DButils(三)使用C3P0实现数据库的连接池_第2张图片

代码地址 https://gitee.com/911711054/JDBCLianJieChiHeDBUtils.git

你可能感兴趣的:(Java)