使用C3P0获取jdbc的连接(相关的总结)

1.首先的创建一个Dynamic Web Project

2.导包

使用C3P0获取jdbc的连接(相关的总结)_第1张图片

3.在src包下创建c3p0-config.xml ,配置文件如下:



	
	com.mysql.jdbc.Driver
	jdbc:mysql://localhost:3306/account
					//3306后面的是要连接的数据库的名
	root
	123
	10
	30
	100
	10
	
	

4.编写数据源工作类C3P0Util,程序如下:

package cn.uplooking.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mysql.jdbc.Statement;

public class C3P0Util {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	
	public static DataSource getDataSource() {
		return dataSource;
	}

	
	
	public static Connection getConnection(){
		
		try {
			return dataSource.getConnection();
		} catch (Exception e) {
			throw new RuntimeException("服务器连接错误");
		}         
		
	}
	public static void release(Connection conn,Statement stmt,ResultSet rs){
		//关闭资源
				if(rs!=null){
					try {
						rs.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					rs = null;
				}
				if(stmt!=null){
					try {
						stmt.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					stmt = null;
				}
				if(conn!=null){
					try {
						conn.close();//关闭
					} catch (Exception e) {
						e.printStackTrace();
					}
					conn = null;
				}
	}



	public static void closes(Connection conn, PreparedStatement ps, Object object) {
		
		
	}
	
 
}

5.创建Test测试类,进行增 删 改 查。

package cn.uplooking.testDBUtils;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import cn.uplooking.pojo.Account;
import cn.uplooking.utils.C3P0Util;


public class test01 {
	//添加
	@Test
	public void test02() throws SQLException{
			//获取queryRunner对象
			QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
			//执行sql
			qr.update("insert into account (id,name,money) values(null,'你好','50')");
			//打印结果
	}
	//修改
	@Test
	public void test03() throws SQLException{
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		String  sql = "update account set name=?,money=? where id=?";
		qr.update(sql,"小米","9000",1);
	
	}
	//删除
	@Test
	public void test04() throws SQLException{
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		qr.update("delete from account where id=2");
	}
	//查询
	@Test
	public void test05() throws SQLException{
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		//这里用到BeanListHandler 意思是返回list集合
		List list = qr.query("select * from  account", new BeanListHandler(Account.class));
		for(Account a :list){
				System.out.println(a);
		}
	}
	
}

所对应的数据库如下:

使用C3P0获取jdbc的连接(相关的总结)_第2张图片

你可能感兴趣的:(使用C3P0获取jdbc的连接(相关的总结))