搬运自己的mysql学习笔记2-连接池的使用

来源:互联网 发布:淘宝苏哥游戏 编辑:程序博客网 时间:2024/05/24 04:38
连接池的作用:
管理数据库连接,提高性能
原理:
连接池初始化时存入一定数量的连接,用的时候通过方法获取,不用的时候归还连接
规范:
所有的连接池必须实现一个接口,javax.sql.DataSourse接口
获取连接的方法:
Connection getConnection()
归还连接的方法:
就是jdbc的释放连接的方法,调用connection.close()方法
常用连接池:

apache组织的DBCP:

需要导入两个jar包1.commons-dbcp-1.4.jar 

2.commons-pool-1.5.6.jar

直接写死或者采用配置文件的方式

package DBCPDemo;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;


import javax.sql.DataSource;


import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;




public class TestDBCP {
public static void main(String[] args) throws Exception {
new TestDBCP().test2();
}
//用硬编码方式使用连接池
public void test1() throws SQLException{
//创建连接池
BasicDataSource ds = new BasicDataSource();
//配置信息
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/mybase");
ds.setUsername("root");
ds.setPassword("123");
Connection con = ds.getConnection();
String sql = "select * from moves where movename like ?";
java.sql.PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "%钢铁侠%");
ResultSet rst = pst.executeQuery();
while(rst.next()){
System.out.println(rst.getString("address"));
}
pst.close();
ds.close();
con.close();

}
//用配置文件的方式使用连接池
public void test2() throws Exception{
//创建配置文件对象
Properties prop = new Properties();
//设置配置文件对象
//prop.setProperty("driverclass", "com.mysql.jdbc.Driver");
prop.load(new FileInputStream("src/JDBC.properties"));
DataSource datasource = new BasicDataSourceFactory().createDataSource(prop);
Connection con = datasource.getConnection();
String sql = "select * from moves where movename like ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "%蜡笔小新%");
ResultSet rst = pst.executeQuery();
while(rst.next()){
System.out.println(rst.getString("address"));
}
pst.close();
rst.close();

con.close();
}
}

配置文件:

driverclass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybase
username = root
password =123

c3p0:

优点,能自动回收闲置连接

导入一个jar包:c3p0-0.9.1.2.jar

配置文件的名称必须为 c3p0.propertie或者c3p0-pconfig.xml

配置文件的路径必须在src目录下,格式如下

c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/mybase
c3p0.user=root
c3p0.password=123

不需要再解析properties文件

ComboPooledDataSource ds = new ComboPooledDataSource();
Connection con = ds.getConnection();
String sql = "select * from moves where movename like ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "%柯南%");
ResultSet rst = pst.executeQuery();
while(rst.next()){
System.out.println(rst.getString("movename"));
}
jdbcUtils.closeConnection(con, pst, rst);
}

0 0