zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    VisualSVN Server 和 Subversion (都是服务器端安装)
    pl/sql导出dmp格式数据时,命令行一闪而退的问题
    Linux各种时间类型与时间函数提供技术文档
    erlang tuple的一些操作
    erlang 题目:一个integer列表,按照数字出现的次数由少到多排序,相同的数字小 的在前面
    一些erlang 题目
    各种排序
    erlang gen_tcp 详细例子
    erlang receive语句大诠释
    ets结合record的增删改查操作
  • 原文地址:https://www.cnblogs.com/qurui1997/p/10639823.html
Copyright © 2011-2022 走看看