Database connection pool (3) dbcp connection pool

dbcp

Download URL

http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi
Insert picture description here

Import connection pool

Right click Build Path
Insert picture description here

Steps

  1. Import connection pool plug-ins, Commons Pool and Commons Logging plug-ins
  2. Define the data source private static BasicDataSource ds;
  3. Define the data source and initialize it in the static code block
调用
con = DBCPDateSource.getConnection();
关闭
finally {
    
    
			
			DBCPDateSource.close(pstmtTwo, pstmtTwo, con);
		}


封装的dbcp数据源代码
package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbcp2.BasicDataSource;

public class DBCPDateSource {
    
    
	private static final String connectionUrl = "jdbc:mysql://localhost:3306/web01?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
	private static final String user = "root";
	private static final String passWord = "121156";
	//定义成员数据源
	private static BasicDataSource ds;

	static {
    
    
		//数据源初始化  放在静态代码块,保证最先执行
		ds = new BasicDataSource();
		ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
		ds.setUrl(connectionUrl);
		ds.setUsername(user);
		ds.setPassword(passWord);
		
		//初始化链接的个数  这里初始化为5个
		ds.setInitialSize(5);
		//最大链接个数   创建链接时,最多同时创建二十个,如果超过二十个,会等其他链接使用完再进行创建
        //防止使用链接过多时,造成性能降低
		ds.setMaxTotal(20);
		//保证连接池里面至少有三个空闲链接  初始化为5个空闲链接,如果有4个人使用,则还有一个空闲链接,此时会自动再生成两个空闲链接做备用
		ds.setMinIdle(3);
	}
 public static Connection getConnection() {
    
    
	 try {
    
    
		return ds.getConnection(); 
		//通过dbcp得到的链接,不用归还,直接关闭就可以。 因为dbcp做了进一步处理,所以关闭的时候不会断开链接,而是归还给连接池
	} catch (SQLException e) {
    
    
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 return null;
 }
 public static void close(ResultSet rs, PreparedStatement pstmt, Connection con) {
    
    
		closeConnection(con);
	}
	//转账操作时,需要关闭两个pstmt,因为他不需要返回结果集,所以不需要设置
	private static void closeConnection(Connection con) {
    
    
		try {
    
    
			if (con != null)
				con.close();
			//这里会把链接归还给jdbc连接池,并不是真正的断开链接
		} catch (SQLException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

Error message

Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class jdbc.DBCPDateSource
Reason : DBCP relies on some methods and classes in Commons Pool and Commons Logging, so
Commons Pool needs to be introduced :
http://commons. apache.org/proper/commons-pool/download_pool.cgi
Commons Logging :
http://commons.apache.org/proper/commons-logging/download_logging.cgi
Insert picture description here

Guess you like

Origin blog.csdn.net/zhang19903848257/article/details/107149098