您的位置:首页 > 编程语言 > Java开发

Java-DBCP连接池使用方法

2017-11-14 09:52 218 查看

一、导包

下载地址:http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi

二、配置文件

配置文件名称:*.properties

配置文件位置:任意,监视src(classpath/类路径)

配置文件内容:properties不能编写中文,不支持在STS中修改,必须使用记事本修改内容,否则中文注释就会乱码

#驱动名
driverClassName=com.mysql.jdbc.Driver
#url
url=jdbc:mysql://127.0.0.1:3306/mydb
#用户名
username=sa
#密码
password=123456

#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1


常见配置项

相关属性说明: http://commons.apache.org/proper/commons-dbcp/configuration.html

三、编写工具类

public class JdbcUtils {
private static DataSource dataSource;
static{
try {
//1.加载找properties文件输入流
InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
//2.加载输入流
Properties props = new Properties();
props.load(is);
//3.创建数据源
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public static DataSource getDataSource(){
return dataSource;
}

public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

public static void release(ResultSet rs, PreparedStatement pstmt, Connection conn){

if(rs!=null){
try {
rs.close();
} catch (SQLException e) {

e.printStackTrace();
}
rs = null;
}

if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {

e.printStackTrace();
}
pstmt= null;
}

if(conn!=null){
try {
conn.close();
} catch (SQLException e) {

e.printStackTrace();
}
conn = null;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: