C3P0连接数据库

方法一:c3p0通过set方法进行配置
1.C3P0下载地址:https://sourceforge.net/projects/c3p0/?source=navbar C3P0是一个开源的连接池。
2.创建c3po.properties配置文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_c3po
username=root
password=lele112233

3.读取配置文件c3po.properties

/**
	 * 根据key获取value
	 * @param key
	 * @return
	 */
	public static String getValue(String key) {
		//创建一个Properties对象
		Properties prop = new Properties();
		//读取配置文件c3p0.properties
		InputStream in = new PropertiesUtil().getClass().getResourceAsStream("/c3p0.properties");
		try {
			prop.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return (String)prop.get(key);
	}

4.配置DataSource,注入属性

 /**
	     * 配置DataSource,用set方法注入属性
	     */
	    public static ComboPooledDataSource setDataSource(){
	    	ComboPooledDataSource dataSource = new ComboPooledDataSource();
	        try {
	            dataSource.setDriverClass(PropertiesUtil.getValue("driverClassName"));
	            dataSource.setJdbcUrl(PropertiesUtil.getValue("url"));
	            dataSource.setUser(PropertiesUtil.getValue("username"));
	            dataSource.setPassword(PropertiesUtil.getValue("password"));
	        } catch (PropertyVetoException e) {
	            e.printStackTrace();
	        }
	        return dataSource;
	    }

5.测试连接

   //测试连接
	    public static void main(String[] args) throws SQLException {
			try {
				Connection C3poConn = setDataSource().getConnection();
			    System.out.println("连接成功");
			    System.out.println(C3poConn);
			}catch (Exception e) {
			    System.out.println("连接失败");
			}
		}

方法二:c3p0通过c3p0-config.xml文件进行配置
1.配置从c3p0-config.xml文件

<?xml version="1.0" encoding="UTF-8"?> root lele123456 jdbc:mysql://localhost:3306/db_druid com.mysql.jdbc.Driver 30000 30 3 30 100 2 200 root lele112233 jdbc:mysql://localhost:3306/db_druid com.mysql.jdbc.Driver 5 20 25 5

2.测试连接

  读取配置文件进行加载获取dataSource
       private static ComboPooledDataSource dataSource = new ComboPooledDataSource("lele");
          //测试连接
           public static void main(String[] args) throws SQLException {
             	//ComboPooledDataSource dataSource = new ComboPooledDataSource("lele");
             	try {
         			Connection C3poConn = dataSource.getConnection();
         		    System.out.println("连接成功");
         		    System.out.println(C3poConn);
         		}catch (Exception e) {
         		    System.out.println("连接失败");
         		}
       }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java程序员劝退师

感谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值