JDBC--connection pool

Use DBCP and C3P0 connection pool operation
through JDBC 1. Use C3P0 connection pool through JDBC
C3P0 is an open source JDBC connection pool, which implements data source and JNDI binding, supports JDBC3 specification and JDBC2 standard extension. Open source projects currently using it include Hibernate, Spring, etc.
For example:
create table t_user(
user_id int primary key auto_increment,
user_name varchar(20),
user_age int,
user_sex bit,
user_address varchar(30),
user_day datetime
);

2. Create Java project
3. Import dependency package
c3p0-0.9.5.2.jar
mchange-commons-java-0.2.15.jar
mysql-connector-java-5.1.38.jar

4. Create c3p0 configuration file under ser [ c3p0-config.xml]

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- c3p0的默认配置项 -->
	<default-config>
    	<property name="driverClass">com.mysql.jdbc.Driver</property>
    	<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
    	<property name="user">root</property>
    	<property name="password">123456</property>
    	<property name="initialPoolSize">5</property>
    	<property name="maxPoolSize">20</property>
  	</default-config>
  	<!-- 定义的数据库配置 -->
  	<named-config name="test"> 
    	<property name="driverClass">com.mysql.jdbc.Driver</property>
    	<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
    	<property name="user">root</property>
    	<property name="password">123456</property>
    	<property name="initialPoolSize">25</property>
    	<property name="maxPoolSize">200</property>
  	</named-config>
</c3p0-config>

5. Create javabean

package com.lx.bean;
/**
 * 保存用户信息的java实体类
 * @author Administrator
 *
 */

import java.sql.Date;

public class UserBean {
	private int userid;
	private String username;
	private int userage;
	private boolean usersex;
	private String useraddress;
	private Date userday;

	public int getUserid() {
		return userid;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getUserage() {
		return userage;
	}

	public void setUserage(int userage) {
		this.userage = userage;
	}

	public boolean isUsersex() {
		return usersex;
	}

	public void setUsersex(boolean usersex) {
		this.usersex = usersex;
	}

	public String getUseraddress() {
		return useraddress;
	}

	public void setUseraddress(String useraddress) {
		this.useraddress = useraddress;
	}

	public Date getUserday() {
		return userday;
	}

	public void setUserday(Date userday) {
		this.userday = userday;
	}
}

6. Create a database access class

package com.lx.dbacsess;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.lx.bean.UserBean;
public class UserAcsess {
	//定义保存c3p0数据源对象
   private ComboPooledDataSource dataSource=null;
   //定义数据库连接对象
   private  Connection  conn=null;
   //定义PreparedStatement 
   private PreparedStatement ps=null;
   public UserAcsess() {
	   //加载c3p0-config.xml文件中默认的config
	   //初始化数据源
	   //dataSource =new ComboPooledDataSource();
	   //初始化数据源,加载的是自定义的数据库表配置项
	   dataSource =new ComboPooledDataSource("test");
       //初始化数据源
	   try {
		conn=dataSource.getConnection();
	   } catch (SQLException e) {
		e.printStackTrace();
	   }
   }
  
   public  void  insertUser(UserBean  userbean) {
	   try {
	   String insertsql="insert into t_user values(null,?,?,?,?,?);";
	   ps=conn.prepareStatement(insertsql);
	   ps.setString(1,userbean.getUsername());
	   ps.setInt(2,userbean.getUserage());
       ps.setBoolean(3,userbean.isUsersex());
       ps.setString(4,userbean.getUseraddress());
       ps.setDate(5,new Date(System.currentTimeMillis()));
       int temp=ps.executeUpdate();
	   if(temp>0)  System.out.println("添加成功");
	   }catch(Exception e) {
		   e.printStackTrace();
	   }finally {
		   try {
			ps.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	   }
	}
   
   public  void  updateUser(UserBean  userbean) {
	   try {
	   String insertsql="update t_user set user_name=?,"
	   		+ "user_age=?,user_sex=?,user_address=?,user_day=?"
	   		+ " where user_id=?";
	   ps=conn.prepareStatement(insertsql);
	   ps.setString(1,userbean.getUsername());
	   ps.setInt(2,userbean.getUserage());
       ps.setBoolean(3,userbean.isUsersex());
       ps.setString(4,userbean.getUseraddress());
       ps.setDate(5,new Date(System.currentTimeMillis()));
       ps.setInt(6,userbean.getUserid());
       int temp=ps.executeUpdate();
	   if(temp>0)  System.out.println("修改成功");
	   }catch(Exception e) {
		   e.printStackTrace();
	   }finally {
		   try {
			ps.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	   }
	}
   
   public  void  deleteUser(int userid) {
	   try {
	   String insertsql="delete from t_user where user_id=?";
	   ps=conn.prepareStatement(insertsql);
       ps.setInt(1,userid);
       int temp=ps.executeUpdate();
	   if(temp>0)  System.out.println("删除成功");
	   }catch(Exception e) {
		   e.printStackTrace();
	   }finally {
		   try {
			ps.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	   }
	}
   
   public  void  selectUser() {
	   try {
	   String selectsql="select* from t_user;";
	   ps=conn.prepareStatement(selectsql);
       ResultSet temp=ps.executeQuery();
	   while(temp.next()) {
		   int userid=temp.getInt("user_id");
		   String username=temp.getString("user_name");
		   int userage=temp.getInt("user_age");
		   boolean usersex=temp.getBoolean("user_sex");
		   String useraddress=temp.getString("user_address");
		   Date userday=temp.getDate("user_day");
	       System.out.println(userid+"\t"+username);
	   }
	   }catch(Exception e) {
		   e.printStackTrace();
	   }finally {
		   try {
			ps.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	   }
	}
}

Advantages: There is no need to manually write the operation of creating a database connection object, because the configuration of the database connection pool of c3p0 has been configured and initialized successfully.
Provide program execution efficiency.
You do not need to modify the source code when you switch the database in the future, you only need to modify the configuration of the c3p0 database connection pool.

2. Use dbcp connection pool through JDBC. The
database connection pool is responsible for allocating, managing and releasing database connections. It allows applications to reuse an existing database connection instead of re-establishing one; releasing database connections whose idle time exceeds the maximum idle time To avoid missing the database connection caused by not releasing the database connection. This technology can significantly improve the performance of database operations.
Examples:

create table t_user(
user_id int primary key auto_increment,
user_name varchar(20),
user_age int,
user_sex bit,
user_address varchar(30),
user_day datetime
);

1. Create a java project
2. Import the jar package
[commons-dbcp-1.4.jar
commons-dbutils-1.6.jar
commons-pool-1.6.jar]

3. Create a database connection configuration file under src [xxxxxxxx.properties]

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
username=root
password=123456
maxActive=50
maxIdle=20
maxWait=60000

4. Create javabean
5. Create database access class

 public UserAscess() {
	   try {
	   Properties pro=new Properties();
	   InputStream inStream=this.getClass().getResourceAsStream("/jdbcdbcp.properties");
	   pro.load(inStream);
	   DataSource ds=BasicDataSourceFactory.createDataSource(pro);
	   conn=ds.getConnection();
	   }catch(Exception e) {
		   e.printStackTrace();
	   }
   }

3. JDBC access to Druid
Druid is first a database connection pool. Druid is currently the best database connection pool. It surpasses other database connection pools in terms of functionality, performance, and scalability, including DBCP, C3P0, BoneCP, Proxool, and JBoss DataSource. Druid has deployed more than 600 applications in Alibaba, and has been rigorously tested in a large-scale production environment for more than a year. Druid is a database connection pool developed by Alibaba called Monitoring!
At the same time, Druid is not only a database connection pool, it includes four parts:
Druid is a JDBC component, which includes three parts:
a plug-in system based on the Filter-Chain model.
DruidDataSource efficient and manageable database connection pool.
Features of SQLParser
Druid
1. Replace DBCP and C3P0. Druid provides an efficient, powerful, and scalable database connection pool.
2. You can monitor database access performance. Druid provides a powerful StatFilter plug-in built-in, which can perform detailed statistics on SQL execution performance, which is helpful for online database access performance analysis.
3. The database password is encrypted. Writing the database password directly in the configuration file is a bad behavior and can easily lead to security problems. Both DruidDruiver and DruidDataSource support PasswordCallback.
4. SQL execution log. Druid provides different LogFilters, which can support Common-Logging, Log4j and JdkLog. You can select the corresponding LogFilter as needed to monitor your application's database access.
5. Extend JDBC. If you have programming requirements for the JDBC layer, you can use the Filter mechanism provided by Druid to easily write extension plug-ins for the JDBC layer.
So Druid can:
1. Act as a database connection pool.
2. You can monitor database access performance.
3. Obtain SQL execution logs.
For example:

create table t_user(
user_id int primary key auto_increment,
user_name varchar(20),
user_age int,
user_sex bit,
user_address varchar(30),
user_day datetime
);

1. Create a java project
2. Import the jar package [druid-1.1.10.jar]
3. Create a database connection configuration file [xxxxxxxx.properties] under src

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
initialSize=100
maxActive=300
maxWait=60000
Druid配置详解
https://blog.csdn.net/zhangjinwei417/article/details/92823438

4. Create javabean
5. Create database access class

  private Connection conn=null;
   private PreparedStatement ps=null;
   public UserAscess() {
	   try {
	   Properties pro=new Properties();
	   InputStream inStream=this.getClass().getResourceAsStream("/druid.properties");
	   pro.load(inStream);
	   DataSource ds=DruidDataSourceFactory.createDataSource(pro);
	   conn=ds.getConnection();
	   }catch(Exception e) {
		   e.printStackTrace();
	   }
   }

Homework: Modify the student management program [JDBC+Druid] done before

Guess you like

Origin blog.csdn.net/guoguo0717/article/details/108873278