c3p0数据库连接池dbutil

本文详细介绍了如何使用C3P0连接池实现数据库连接的高效管理,并提供了关键代码片段,包括数据库连接的获取、释放及错误处理,旨在提高应用性能与资源利用效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn.secondteam.utils;
import java.beans.PropertyVetoException;

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

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DbUtil {
	final static String HOST = "127.0.0.1";
	final static String NAME = "root";
	final static String PSW = "root";
	static final String DBNAME = "bbsdb";
	private static Connection connection;
	public static ComboPooledDataSource dsWebgame;
	static {
		dsWebgame = new ComboPooledDataSource();
               try {
                  dsWebgame.setDriverClass(DRIVER);
               } catch (PropertyVetoException e) {
                  e.printStackTrace();
              } 
              // 参数由 Config 类根据配置文件读取
              dsWebgame.setJdbcUrl(URL);
             // 设置数据库的登录用户名
             dsWebgame.setUser(USERNAME);
             // 设置数据库的登录用户密码
             dsWebgame.setPassword(PASSWORD);
             // 设置连接池的最大连接数
             dsWebgame.setMaxPoolSize(35);
             // 设置连接池的最小连接数
             dsWebgame.setMinPoolSize(20);
             // 有时候会产生死锁,将maxStatements设置为0
             dsWebgame.setMaxStatements(0);
             //小于MySQL的wait timeout即可。 
             dsWebgame.setIdleConnectionTestPeriod(120);
	}

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 */
	public static  Connection getConnection() {
              if (null == connection) {
                 connection=newConnection();
              } 
              try {
                 if(connection.isClosed()){
                    connection=dsWebgame.getConnection();
                }
             } catch (SQLException e) {
                e.printStackTrace();
             }
             return connection;
        }
	/**
	 * 创建数据库连接
	 * @return
	 */
	private static Connection newConnection() {
		try {
			return (Connection) dsWebgame.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	public static void main(String args[]){
		getConnection();
	}
	/**
	 * 释放资源
	 * @param conn
	 * @param st
	 * @param rs
	 */
	public static void release(Connection con, 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 (con != null) {
			try {
				con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值