欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DBUtils的查询操作代码实例

程序员文章站 2022-03-27 12:23:10
...
package dBUtils;

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

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

import c3p0.c3p0工具类;

public class DBUtils查询操作 {
	/**
	 * 查询所有用户总个数
	 */
	@Test
	public void testQueryCount() {
		try {
		//创建核心QueryRunner
		QueryRunner qr = new QueryRunner(c3p0工具类.getDataSource());
		//2.编写sql语句
		String sql = "select count(*)from user";
		//执行查询操作
		long count =  (long) qr.query(sql, new ScalarHandler());
		System.out.println(count);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 根据id查询用户方法
	 */
	@Test
	public void testQueryUserByid() {
		try {
		//创建核心QueryRunner
		QueryRunner qr = new QueryRunner(c3p0工具类.getDataSource());
		//2.编写sql语句
		String sql = "select *from user where uid=?";
		//3.设置占位符
		Object[] params = {2};
		//3.执行语句
		User user =  qr.query(sql, new BeanHandler<User>(User.class), params);
		//4.对结果集合进行遍历
		 System.out.println(user.getUname()+"—---"+user.getPrice());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 查询所有数据
	 */
	@Test
	public void testQueryAllUser() {
		try {
		//创建核心QueryRunner
		QueryRunner qr = new QueryRunner(c3p0工具类.getDataSource());
		//2.编写sql语句
		String sql = "select *from user";
		//3.执行语句
		 List<User> users = qr.query(sql, new BeanListHandler<User>(User.class));	
		//4.对结果集合进行遍历
		 for(User user:users) {
			 System.out.println(user.getUname()+"—---"+user.getPrice());
		 }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}