• 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

  • 相关阅读:
    哈希表详解
    简单字典实现(KV问题)
    【数据结构】——搜索二叉树的插入,查找和删除(递归&非递归)
    【数据结构】——堆及其应用
    初学者的迷茫
    【数据结构】顺序表和链表
    程序运行机理
    回调函数到底是怎么一回事呢?
    C语言中函数可变参数解析
    《剑指offer》数组中出现次数超过数组长度一半的数字
  • 原文地址:https://www.cnblogs.com/qurui1997/p/10639823.html
Copyright © 2020-2023  润新知