Java EE development Chapter 6: Using JDBC development of DBCP connection pool

Introduction: Connection Pool Management database connection, the role is to improve the performance of the project. It is credited certain number of connections in the connection pool is initialized when the use of time by means of acquisition, when not return connection. Connection pooling is commonly used DBCP and C3P0, in this section we look first to understand the use of DBCP connection pool.

-------- using the steps ------

1. Import jar package (commons-dbcp-1.4.jar and commons-pool-1.5.6.jar) (your own download Baidu)


2. Use api

a. hardcoded

//创建连接池
BasicDataSource ds = new BasicDataSource();
					
//配置信息
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql:///day07");
ds.setUsername("root");
ds.setPassword("1234");

b. Profiles

实现编写一个properties文件
//存放配置文件
Properties prop = new Properties();
prop.load(new FileInputStream("src/dbcp.properties"));
//设置
//prop.setProperty("driverClassName", "com.mysql.jdbc.Driver");
					
//创建连接池
DataSource ds = new BasicDataSourceFactory().createDataSource(prop);
------ code to achieve Demo ----

1, adding hardware decoding data (database using the " Chapter IV Java EE development: basic using JDBC "):

	@Test
	//硬编码
	public void f1() throws Exception{
		//创建连接池
		BasicDataSource ds = new BasicDataSource();
		
		//配置信息
		ds.setDriverClassName("com.mysql.jdbc.Driver");
		ds.setUrl("jdbc:mysql:///day07");
		ds.setUsername("root");
		ds.setPassword("123");
		
		Connection conn=ds.getConnection();
		String sql="insert into category values(?,?);";
		PreparedStatement st=conn.prepareStatement(sql);
		
		//设置参数
		st.setString(1, "c0191");
		st.setString(2, "饮p料");
		
		int i = st.executeUpdate();
		System.out.println(i);
		//JdbcUtils.closeResource(conn, st, null);
	}

2, the configuration file to add data:


	@Test
	public void f2() throws Exception{
		//存放配置文件
		Properties prop = new Properties();
		prop.load(new FileInputStream("src/dbcp.properties"));
		//设置
		//prop.setProperty("driverClassName", "com.mysql.jdbc.Driver");
		
		//创建连接池
		DataSource ds = new BasicDataSourceFactory().createDataSource(prop);
		
		Connection conn=ds.getConnection();
		String sql="insert into category values(?,?);";
		PreparedStatement st=conn.prepareStatement(sql);
		
		//设置参数
		st.setString(1, "c012");
		st.setString(2, "饮料1");
		
		int i = st.executeUpdate();
		System.out.println(i);
		//JdbcUtils.closeResource(conn, st, null);
	}
-----Finish------


Published 105 original articles · won praise 74 · views 70000 +

Guess you like

Origin blog.csdn.net/qq_32306361/article/details/78028620