首页 > 数据库技术 > 详细

java C3P0连接数据库

时间:2019-04-01 22:59:38      阅读:146      评论:0      收藏:0      [点我收藏+]
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

java C3P0连接数据库

原文:https://www.cnblogs.com/qurui1997/p/10639823.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!