JDBC连接数据库(使用连接池)

===JDBC连接Mysql数据库
通过dbcp连接池获取连接对象
导入包:
commons-dbutils-1.7.jar 工具包   (可百度搜索Commons DbUtils进行下载)
mysql-connector-java-5.1.37-bin (连接包)
commons-dbcp-1.4 dbcp工具包 和 commons-pool-1.6 (辅助包)

1、=======配置文件
配置文件名称:名称.properties
配置文件位置:任意,建议src(classpath/类路径)
如:db.properties配置文件
driverClassName=com.mysql.jdbc.Driver
                               //数据库名  
url=jdbc:mysql://localhost:3306/mysql01?useUnicode=true&characterEncoding=utf-8
username=root //数据库登录名
password=root  //密码
initialSize=10
maxActive=50
maxIdle=20
minIdle=5
maxWait=20000

2、====获取数据源对象、获取数据源连接、返回数据源

//创建DBCPUtils 类进行封装

public class DBCPUtils {
//定义数据源对象
private static DataSource ds;
//静态代码块在DBCPUtils类加载时自动调用一次。
static{
try { 加载properties文件,获得Properties对象
System.out.println("静态代码块调用。。。。");
//读取配置文件信息
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("properties/db.properties");
//实例化properties对象
Properties pr = new Properties();
//从输入流中读取属性列表(键和元素对)
pr.load(is);
//获取数据源对象
ds = BasicDataSourceFactory.createDataSource(pr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**

* @Title: getDataSource  
* @Description: 获取数据源对象  
* @return
*/
public static DataSource getDataSource(){
return ds;
}
/**

* @Title: getConnection  
* @Description: 根据数据源获取连接对象
* @return
*/
public static Connection getConnection(){
Connection conn = null;
try {
conn = ds.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
/**

* @Title: close  
* @Description: 关闭连接
* @param conn
*/
public static void close(Connection conn){
try {
DbUtils.close(conn);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值