您的位置:首页 > 其它

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

2017-08-17 18:36 495 查看

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

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

用此连接池需要配置文件

配置文件名称:*.properties

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

配置文件内容: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 except
4000
ion
throw new RuntimeException(e);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐