DBUtils连接池
DBCP连接池
需要两个java包
dbcp。jar
pool。jar
工具类
public class JDBCUtils {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/daydb";
public static final String USERNAME = "root";
public static final String PASSWORD = "root";
/*
* 创建连接池BasicDataSource
*/
public static BasicDataSource dataSource = new BasicDataSource();
//静态代码块
static {
//对连接池对象 进行基本的配置
dataSource.setDriverClassName(DRIVER); // 这是要连接的数据库的驱动
dataSource.setUrl(URL); //指定要连接的数据库地址
dataSource.setUsername(USERNAME); //指定要连接数据的用户名
dataSource.setPassword(PASSWORD); //指定要连接数据的密码
}
/*
* 返回连接池对象
*/
public static DataSource getDataSource(){
return dataSource;
}
}
测试类
* 演示使用DBUtils工具 完成数据库表的增加操作
*/
public class Demo {
// 插入功能
@Test
public void insert(){
try {
//获取一个用来执行SQL语句的对象 QueryRunner
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
String sql = "INSERT INTO zhangwu(name,money,parent) VALUES(?,?,?)";
Object[] params = {"股票收入", 5500, "收入"};
int line = qr.update(sql,params);
//结果集处理
System.out.println("line = " + line);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//删除功能
@Test
public void delete(){
try {
//创建一个QueryRunner对象,用来完成SQL语句的执行
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
//执行SQL语句
String sql = "DELETE FROM zhangwu WHERE name = ?";
Object[] params = {"股票收入"};
int line = qr.update(sql, params);
//结果集的处理
System.out.println("line="+line);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//更新功能
@Test
public void update(){
try {
//创建一个QueryRunner对象,用来完成SQL语句的执行
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
//执行SQL语句
String sql = "UPDATE zhangwu SET money = money+1000 WHERE name=?";
Object[] params = {"股票收入"};
int line = qr.update(sql, params);
//结果集的处理
System.out.println("line="+line);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//查询功能,将结果集中第一条记录封装到一个指定的javaBean中。
@Test
public void search(){
try{
//获取QueryRunner
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
//执行SQL语句
String sql = "SELECT * FROM zhangwu";
Object[] params = {};
Product p = qr.query(sql, new BeanHandler<Product>(Product.class), params);
//结果集处理
System.out.println(p);
} catch(SQLException e){
throw new RuntimeException(e);
}
}
}