码迷,mamicode.com
首页 > 数据库 > 详细

3中建立数据库连接池dbcp和c3p0和tomcat数据池

时间:2015-04-05 17:29:22      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

 

DBCP数据源:需要

Commons-dbcp.jar:连接池的实现
Commons-pool.jar:连接池实现的依赖库

dbcpconfig.properties(这个在src同目录下--模板

#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc
username=root
password=

#<!-- 初始化连接 -->
initialSize=10

#最大连接数量
maxActive=50

#<!-- 最大空闲连接 -->
maxIdle=20

#<!-- 最小空闲连接 -->
minIdle=5

#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000


#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] 
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=gbk

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED

JdbcUtils_DBCP.java

package cn.lcp.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;


public class JdbcUtils_DBCP {
    
    private static DataSource ds = null;
    static{
        try{
            InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties prop = new Properties();
            prop.load(in);
            
            BasicDataSourceFactory factory = new BasicDataSourceFactory();
            
            ds = factory.createDataSource(prop);
            System.out.println(ds);
        }catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    
    public static Connection getConnection() throws SQLException{
        
        return ds.getConnection();
    }
    
    public static void release(Connection conn,Statement st,ResultSet rs){
        
        
        if(rs!=null){
            try{
                rs.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;

        }
        if(st!=null){
            try{
                st.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if(conn!=null){
            try{
                conn.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
}

demo.java

package cn.lcp.demo;

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

import cn.lcp.utils.JdbcUtils_DBCP;

//模拟转账
public class demo {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        Savepoint sp = null;
        try {
            conn = JdbcUtils_DBCP.getConnection();
            // 执行多条sql语句,开启事务
            conn.setAutoCommit(false); // start transaction

            String sql1 = "update account set money=money-100 where name=‘aaa‘";
            // 预编译sql语句
            st = conn.prepareStatement(sql1);
            st.executeUpdate();

            
            //设置事务回滚点
            sp = conn.setSavepoint();
            
            String sql2 = "update account set money=money+100 where name=‘bbb‘";
            st = conn.prepareStatement(sql2);
            st.executeUpdate();
            
            //int i = 10 / 0;  //这里出现异常,到catch里面执行回滚
            
            String sql3 = "update account set money=money+100 where name=‘ccc‘";
            st = conn.prepareStatement(sql3);
            st.executeUpdate();

            //提交事务
            conn.commit();
            System.out.println("成功!!!"); // log4j

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils_DBCP.release(conn, st, rs);
        }
    }
}

加入dbcp链接池
1.导入jar包
commons-dbcp-1.2.2.jar commons-pool.jar

2、在类目录下加入dbcp的配置文件:dbcpconfig.properties

3、在jdbcUtils的静态代码块中创建池

private static DataSource ds = null;
static{
  try{
    InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
    Properties prop = new Properties();
    prop.load(in);

  BasicDataSourceFactory factory = new BasicDataSourceFactory();

  ds = factory.createDataSource(prop);
  System.out.println(ds);
  }catch (Exception e) {
    throw new ExceptionInInitializerError(e);
  }
}

 

使用DBCP示例代码:
static{
    InputStream in = JdbcUtil.class.getClassLoader().
            getResourceAsStream("dbcpconfig.properties");
    Properties prop = new Properties();
    prop.load(in);

    BasicDataSourceFactory factory = new BasicDataSourceFactory();
    dataSource = factory.createDataSource(prop);
}

 

 

 

C3P0 数据源

需要c3p0-pre.jar和mchange-commons.jar两个包。(这个xml在src同目录下)

c3p0-config.xml(可以当成模板)
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day16</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>
 -->    
    <named-config name="mysql">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day16</property>
        <property name="user">root</property>
        <property name="password">lcp8090</property>
    
        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </named-config>
    
    <!--  
    <named-config name="oracle">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day16</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>

JdbcUtils-C3P0.java

package cn.lcp.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import com.mchange.v2.c3p0.ComboPooledDataSource;


public class JdbcUtils_C3P0 {
    
    private static ComboPooledDataSource ds = null;
    static{
        try{            
            ds = new ComboPooledDataSource("lcp");
            
        }catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    
    public static Connection getConnection() throws SQLException{
        
        return ds.getConnection();
    }
    
    public static void release(Connection conn,Statement st,ResultSet rs){
        
        
        if(rs!=null){
            try{
                rs.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;

        }
        if(st!=null){
            try{
                st.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
            
        }
        
        if(conn!=null){
            try{
                conn.close();
            }catch (Exception e) {
                e.printStackTrace();
            }    
        }
    }
}

demo.java

package cn.lcp.demo;

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

import cn.lcp.utils.JdbcUtils_C3P0;
import cn.lcp.utils.JdbcUtils_DBCP;

//模拟转账
public class demo {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        Savepoint sp = null;
        try {
            conn = JdbcUtils_C3P0.getConnection();
            // 执行多条sql语句,开启事务
            conn.setAutoCommit(false); // start transaction

            String sql1 = "update account set money=money-100 where name=‘aaa‘";
            // 预编译sql语句
            st = conn.prepareStatement(sql1);
            st.executeUpdate();

            
            //设置事务回滚点
            sp = conn.setSavepoint();
            
            String sql2 = "update account set money=money+100 where name=‘bbb‘";
            st = conn.prepareStatement(sql2);
            st.executeUpdate();
            
            //int i = 10 / 0;  //这里出现异常,到catch里面执行回滚
            
            String sql3 = "update account set money=money+100 where name=‘ccc‘";
            st = conn.prepareStatement(sql3);
            st.executeUpdate();

            //提交事务
            conn.commit();

            System.out.println("成功!!!"); // log4j

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils_C3P0.release(conn, st, rs);
        }
    }
}

 

 

 

 

 

tomcat连接池:tomcat在运行时只会找自己的lib下的驱动,所以要把数据库连接驱动放到tomcat的lib文件夹下面。

context-xml,在WEB-INF目录下。(模板)

<Context>
  <Resource name="jdbc/EmployeeDB"
            auth="Container"
            type="javax.sql.DataSource"
            
            username="root"
            password="lcp8090"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/day16"
            maxActive="8"
            maxIdle="4"/>
</Context>

ServletDemo.java

package cn.lcp.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.lcp.dao.BaseDao;

public class ServletDemo1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        BaseDao dao = new BaseDao();
        dao.add();

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

}

BaseDao.java

package cn.lcp.dao;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class BaseDao {

    
    public void add(){
        try{
            Context initCtx = new InitialContext();  //初始化jndi
            Context envCtx = (Context) initCtx.lookup("java:comp/env");  //得到jndi容器
            DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB");  //从容器中检索链接池
    
            Connection conn = ds.getConnection();
            System.out.println(conn);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

3中建立数据库连接池dbcp和c3p0和tomcat数据池

标签:

原文地址:http://www.cnblogs.com/lcpholdon/p/4394311.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!