使用C3P0连接数据库

时间:2022-07-28
本文章向大家介绍使用C3P0连接数据库,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在WEB-INF下导入lib,在lib下放入使用到的jar包

导入

2.在src下写一个c3p0的xml文件

注意要修改一下xml文件,改成自己的数据库:(我的叫myshop)

<property name="jdbcUrl">jdbc:mysql://localhost:3306/myshop?useSSL=true&amp;characterEncoding=UTF-8</property>

还有自己数据库的用户名和密码:(我的都是root)

<property name="user">root</property>
<property name="password">root</property>

我的完整c3p0-config.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/myshop?useSSL=true&amp;characterEncoding=UTF-8</property>
		<property name="user">root</property>
		<property name="password">root</property>
		<property name="checkoutTimeout">30000</property>
		<property name="initialPoolSize">10</property>
		<property name="maxIdleTime">30</property>
		<property name="maxPoolSize">100</property>
		<property name="minPoolSize">10</property>
	</default-config> 
	
</c3p0-config>

3.创建测试类测试链接

package test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * zt
 * 2020/9/14
 * 17:40
 */
public class MyTest {
    static DataSource dataSource;
    public static DataSource getDataSource(){
        dataSource = new ComboPooledDataSource();
        return dataSource;
    }

    public static void main(String[] args) throws SQLException {
        System.out.println(getDataSource().getConnection());
    }
}

出现如下运行结果代表使用c3p0链接成功