C3p0 database connection pool configuration tutorial and MySQL query examples in Eclipse (20200807)

C3p0 database connection pool configuration tutorial and MySQL query examples in Eclipse

1. Check the MySQL installation version and prepare the dependent jar package

MySQL installation version (Community Edition): 8.0.20

Insert picture description here
Insert picture description here

The three required jar packages:

 c3p0-0.9.5.2.jar、mchange-commons-java-0.2.20.jar和mysql-connector-java-8.0.20.jar

Insert picture description here

2. Create a new C3p0-config.xml configuration file

       代码内容如下图所示(主要以命名配置为例(MySQLdb)进行测试连接MySQL数据库):
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
		<property name="jdbcUrl">
			jdbc:mysql://localhost:3306/infomationsystem?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=FALSE&amp;serverTimezone=UTC
		</property>
		<property name="user">root</property>
		<property name="password">123456</property>
		<property name="acquireIncrement">5</property>
		<property name="initialPoolSize">10</property>
		<property name="minPoolSize">10</property>
		<property name="maxPoolSize">20</property>
	</default-config> 
	<!--named-config的name属性值用于传递构造方法中去 -->
	<named-config name="MySQLdb">
		<property name="user">root</property>
		<property name="password">123456</property>
		<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
		<property name="jdbcUrl">
			jdbc:mysql://localhost:3306/infomationsystem?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=FALSE&amp;serverTimezone=UTC
		</property>
   		<property name="acquireIncrement">5</property>
   		<property name="initialPoolSize">10</property>
   		<property name="minPoolSize">5</property>
   		<property name="maxPoolSize">20</property>
	</named-config>
</c3p0-config>

Three, create a new DataSourceUtil class (.java) to test the database connection pool

package com.test.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils 
{
    
    
	private static DataSource dataSource = new ComboPooledDataSource("MySQLdb");
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	// 直接可以获取一个连接池
	public static DataSource getDataSource()
	 {
    
    
		return dataSource;
	}
	// 获取连接对象
	public static Connection getConnection() throws SQLException 
	{
    
    
		Connection con = tl.get();
		if (con == null) 
		{
    
    
			con = dataSource.getConnection();
			tl.set(con);
		}
		return con;
	}
	// 开启事务
	public static void startTransaction() throws SQLException 
	{
    
    
		Connection con = getConnection();
		if (con != null) {
    
    
			con.setAutoCommit(false);
		}
	}
	// 事务回滚
	public static void rollback() throws SQLException 
	{
    
    
		Connection con = getConnection();
		if (con != null) 
		{
    
    
			con.rollback();
		}
	}
	// 提交并且 关闭资源及从ThreadLocall中释放
	public static void commitAndRelease() throws SQLException 
	{
    
    
		Connection con = getConnection();
		if (con != null) 
		{
    
    
			con.commit(); // 事务提交
			con.close();// 关闭资源
			tl.remove();// 从线程绑定中移除
		}
	}
	// 关闭资源方法
	public static void closeConnection() throws SQLException 
	{
    
    
		Connection con = getConnection();
		if (con != null) {
    
    
			con.close();
		}
	}
	public static void closeStatement(Statement st) throws SQLException 
	{
    
    
		if (st != null) 
		{
    
    
			st.close();
		}
	}
	public static void closeResultSet(ResultSet rs) throws SQLException 
	{
    
    
		if (rs != null) {
    
    
			rs.close();
		}
	}
	public static void main(String[] args) 
	{
    
    
		try 
		{
    
    
			System.out.println(getConnection().toString());
		} catch (SQLException e) 
		{
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

DataSourceUtil.java running results

Insert picture description here
Note: If these similar codes (com.mchange.v2.c3p0.impl.NewProxyConnection@9660f4e [wrapping: com.mysql.jdbc.JDBC4Connection@5a8806ef]) appear in the Java console and no error is reported, then the C3P0 database connection to MySQL is configured It succeeded.

Four, specific call examples

    为了更好地利用SQL语句来查询MySQL数据库中表中的内容;
    下面以dic类为例,介绍如何利用DataSourceUtil类和DicDao类来进行基于C3p0连接池的MySQL数据库查询;
    (用到QueryRunner),需要包含commons-dbutils-1.4.jar这个jar包。

The first step is to create a new Dic class

package com.test.lei;

public class Dic 
{
    
    
	private int ID;
	private String CATEGORY;
	private String CNNAME;
	private String ENNAME;
	public int getID() 
	{
    
    
		return ID;
	}
	public void setID(int iD) 
	{
    
    
		ID = iD;
	}
	public String getCATEGORY() 
	{
    
    
		return CATEGORY;
	}
	public void setCATEGORY(String cATEGORY) 
	{
    
    
		CATEGORY = cATEGORY;
	}
	public String getCNNAME() 
	{
    
    
		return CNNAME;
	}
	public void setCNNAME(String cNNAME) 
	{
    
    
		CNNAME = cNNAME;
	}
	public String getENNAME() 
	{
    
    
		return ENNAME;
	}
	public void setENNAME(String eNNAME) 
	{
    
    
		ENNAME = eNNAME;
	}
	@Override
	public String toString() 
	{
    
    
		return "Dic [ID=" + ID + ", CATEGORY=" + CATEGORY + ", CNNAME=" + CNNAME + ", ENNAME=" + ENNAME + "]";
	}
}

The second step is to create a new MySQL data table based on the Dic class as follows:

Insert picture description here

The third step is to create a new DicDao class to execute the query

/*  */
package com.test.dao;

import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.test.lei.Dic;
import com.test.utils.DataSourceUtils;

public class DicDao 
{
    
    
	public List<Dic> findDicList() throws SQLException 
	{
    
    
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from MyDic";
		List<Dic> dicList = runner.query(sql,new BeanListHandler<Dic>(Dic.class));
		return dicList;
	}
	public static void main(String[] args) throws SQLException
	{
    
    
		DicDao d = new DicDao();
		for(int i = 0;i<d.findDicList().size();i++)
		System.out.println(d.findDicList().get(i));
	}
}

The fourth step is to view the results obtained after executing the query

Insert picture description here
So far, it can be seen that the query result is consistent with the content in our newly created MySQL database table, and the method is effective!

Guess you like

Origin blog.csdn.net/jing_zhong/article/details/107867013