美文网首页JavaWeb
SubList分页-006-jdbcUtils类

SubList分页-006-jdbcUtils类

作者: 53b3f4658edc | 来源:发表于2017-11-06 15:05 被阅读10次
  1. 导入c3p0-0.9.1.2、commons-dbutils-1.4、mysql-connector-java-5.1.7-bin

  2. 新建c3p0-config.xml,配置数据库连接信息

<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>
    <!-- 配置名 -->
  <named-config name="newMem"> 
        <!-- 数据库连接名 -->
        <property name="user">root</property>
        <!-- 数据库连接密码 -->
        <property name="password">123123</property>
        <!-- MySQL驱动  -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <!-- 数据库URL:这里的 useUnicode=true要加上&amp;-->
        <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/Mushroom?useUnicode=true&amp;characterEncoding=utf-8</property>
        
       <!-- 连接不够时,一次增长的连接数 -->
        <property name="acquireIncrement">5</property>
       <!-- 连接池初始化连接的个数 --> 
       <property name="initialPoolSize">10</property>
       <!-- 最小连接数 -->
        <property name="minPoolSize">10</property> 
        <!-- 最大连接数 -->
        <property name="maxPoolSize">50</property>
        <!-- 最多可以使用的Statement个数 -->
        <property name="maxStatements">20</property> 
        <!-- 一个连接最多可以使用的Statement个数 -->
        <property name="maxStatementsPerConnection">5</property>
        
   </named-config>
    
</c3p0-config>
  1. 实现jdbcUtils类
package top.itcourse.page.utils;

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

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/*
 * JDBCUtils类构建:
 *      1.导包
 *      2.配置c3p0-config.xml
 *      3.新建静态DataSource对象
 *      4.新建获取Connection的静态方法getConnection
 *      5.新建释放Connection的静态方法relase
 */
public class JDBCUtils {
    
    // 3.新建静态DataSource对象
    private static DataSource dataSource = null;
    static {
        // newMem是c3p0-config.xml中的named-config
        dataSource = new ComboPooledDataSource("newMem");
    }
    
    // 4.新建获取Connection的静态方法getConnection
    public static Connection getConnection() {
        
        Connection connection = null;
        
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            System.err.println("新建Connection时出现异常~~~~~~~~~~~");
        } 
            
        return connection;
    }
    
    // 5.新建释放Connection的静态方法relase
    public static void relase(Connection connection) {
        if (connection != null ) {
            try {
                connection.close();
            } catch (SQLException e) {
                System.err.println("释放Connection时出现异常~~~~~~~");
            }
            
        }
    }
}
 

源码下载

关注下方的微信公众号,回复:java_div_page.code





欢迎加入交流群:451826376


更多信息:www.itcourse.top

完整教程PDF版本下载

相关文章

网友评论

    本文标题:SubList分页-006-jdbcUtils类

    本文链接:https://www.haomeiwen.com/subject/xaslmxtx.html