DBUtils工具类的使用

xiaoxiao2021-02-28  36

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  * <p>Description: 学习使用dbutils进行CRUD</p> public class TestDButils { //查询所有 @Test public void test1() throws SQLException{ /** * 第一种查询方式;要求实例化QueryRunner的时候,传入dataSource,执行sql的时候,不需要传递connection */ // QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDS()); //查询 // List<EE> list = queryRunner.query("select * from ee", new BeanListHandler<>(EE.class)); // for (EE ee : list) { // System.out.println(ee); // } /** * 第二种方式 */ QueryRunner queryRunner = new QueryRunner(); List<EE> 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]); } }
转载请注明原文地址: https://www.6miu.com/read-2622570.html

最新回复(0)