java C3P0连接数据库

package com.jdbc.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3p0 {
	private ComboPooledDataSource cpds;
	private static C3p0 c3p0;

	static {
		c3p0=new C3p0();
	}
	
	/**
	 * 构造方法初始化 配置文件
	 */
	public C3p0() {
		cpds=new ComboPooledDataSource();
		//加载配置文件
		Properties props = new Properties();
		try {
			props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
			cpds.setDriverClass(props.getProperty("mysqlDriver"));
			cpds.setJdbcUrl(props.getProperty("mysqlUrl"));
			cpds.setUser(props.getProperty("mysqlUser"));
			cpds.setPassword(props.getProperty("mysqlPassword"));
			
			cpds.setMaxPoolSize(Integer.parseInt(props.getProperty("MaxPoolSize")));
			cpds.setMinPoolSize(Integer.parseInt(props.getProperty("MinPoolSize")));
			cpds.setInitialPoolSize(Integer.parseInt(props.getProperty("InitialPoolSize")));
			cpds.setMaxStatements(Integer.parseInt(props.getProperty("MaxStatements")));
			cpds.setMaxIdleTime(Integer.parseInt(props.getProperty("MaxIdleTime")));
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}

	}
	/**
	 * 返回连接池的实例
	 * @return
	 */
	public static C3p0 getInstance(){
		
		return c3p0;
	}
	
	
	public Connection getConnection(){
		Connection conn = null;
		try {
			conn = cpds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
                                                                                          	
	public static void main(String[] args) {
		
		Connection connection = C3p0.c3p0.getConnection();
		System.out.println("已经连接成功");
		try {
			System.out.println(connection.getCatalog());
		} catch (SQLException e) {

			e.printStackTrace();
		}
 
	}



}

  db.properties文件

mysqlDriver=com.mysql.jdbc.Driver
mysqlUrl=jdbc\:mysql\://localhost\:3306/test
mysqlUser=root
mysqlPassword=123456

MaxPoolSize = 20
MinPoolSize = 2
InitialPoolSize = 5
MaxStatements = 30

转载于:https://www.cnblogs.com/qurui1997/p/10639823.html

你可能感兴趣的:(java C3P0连接数据库)