(四)JDBC连接池&DBUtils—DBCP连接池的使用

(四)JDBC连接池&DBUtils—DBCP连接池的使用

DBCP也是一个开源的连接池,是Apache Common成员之一,在企业开发中也比较常见,tomacat内置的连接池

用此连接池需要配置文件

配置文件名称:*.properties

配置文件位置:任意,建议srcclasspath/类路径)

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

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/web08?useUnicode=true&characterEncoding=utf8

username=root

password=123456

 

 

DBCP工具类

public class DBCPUtils {
	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) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}

	}
	
	public static DataSource getDataSource(){
		return dataSource;
	}
	
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
}
public class TestDBCP {
	@Test
	public void testUpdataUserById(){
		Connection conn=null;
		PreparedStatement pstmt=null;
		try {
			//获取链接
			conn=DBCPUtils.getConnection();
			//sql语句
			String sql="update tbl_user set upassword=? where uid=?";
			//处理sql语句对象
			pstmt=conn.prepareStatement(sql);
			//对占位符进行处理
			pstmt.setString(1, "亚");
			pstmt.setInt(2,10);
			//处理结果
			int rows=pstmt.executeUpdate();
			if(rows>0){
				System.out.println("更新成功");
			}else{
				System.out.println("更新失败");
			}
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e); 
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值