DBUtils工具类的使用

package com.baidu.test;


import java.sql.SQLException;
import java.util.List;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;


import com.baidu.pojo.EE;
import com.baidu.utils.JDBCUtils;


/**
 * 
* @ClassName: TestDButils 
*

Description: 学习使用dbutils进行CRUD



public class TestDButils {



//查询所有
@Test
public void test1() throws SQLException{

/**
* 第一种查询方式;要求实例化QueryRunner的时候,传入dataSource,执行sql的时候,不需要传递connection
*/

// QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDS());
//查询
// List list = queryRunner.query("select * from ee", new BeanListHandler<>(EE.class));
// for (EE ee : list) {
// System.out.println(ee);
// }


/**
* 第二种方式
*/
QueryRunner queryRunner = new QueryRunner();
List list = queryRunner.query(JDBCUtils.getConnection(),"select * from ee", new BeanListHandler<>(EE.class));
for (EE ee : list) {
System.out.println(ee);
}



//返回单个对象
@Test
public void test2() throws SQLException{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDS());
EE ee = queryRunner.query("select * from ee where id=1", new BeanHandler<>(EE.class));
System.out.println(ee);


}

//传递参数问题
@Test
public void test3() throws SQLException{
/**
* 注意:返回结果的pojo的属性名称必须和列名保持一致
*/

QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDS());
Object[] params={1,"aa"};
EE ee = queryRunner.query("select * from ee where id=? and name=?",params, new BeanHandler<>(EE.class));
System.out.println(ee);


}


//增删改
@Test
public void test4() throws SQLException{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDS());
queryRunner.update("update ee set name=? where id=?", "admin",1);

}

//获取总页数(终结版)
@Test
public void test5() throws SQLException{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDS());
Object[] query = queryRunner.query("select count(*) from ee", new ArrayHandler());
System.out.println(query[0]);

}


}

你可能感兴趣的:(DBUtils工具类的使用)