论坛首页 Java企业应用论坛

dbutils使用示例代码

浏览 5952 次
精华帖 (0) :: 良好帖 (2) :: 新手帖 (1) :: 隐藏帖 (2)
作者 正文
   发表时间:2011-06-04   最后修改:2011-06-08

今天把commons-dbutils-1.3的源码看了一遍
然后写了以下的示例代码

数据库用的是MS SQL SERVER 2005
就建立了三张表做测试

小工具用来起就是方便

学习这个小工具的源码是学习hibernate源码的一个很好的阶梯


这张是数据库表,一共三张,每个表的ID都是自动增长列



这个是项目结构


测试代码
package com.jdbc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.jdbc.db.DBConnection;
import com.jdbc.entity.Book;
import com.jdbc.entity.School;
import com.jdbc.entity.Student;

public class Test {

	public static void main(String[] args) {

		Test t = new Test();

        // dbutils 自带的一个结果集处理类,只把查询结果的第一行封装成数组
		t.testArrayHandler();
 
        // dbutils 自带的一个结果集处理类,把查询结果的每一个行都封装到数组再把数组装到集合中
		t.testArrayListHandler();

        // dbutils 自带的一个结果集处理类,把查询结果封装在bean中
		t.testBeanHandler();
                  
        // dbutils 自带的一个结果集处理类,把查询结果封装在bean中再把bean装到集合中
		t.testBeanListHandler();
                  
        // 两个表查封装到一个bean中
		t.queryTwoTable();

        // 把两个表联查的每行数据封装到bean中再装入集合
		t.queryListTwoTable();

        // 3个表联查封装成级联bean
		t.queryListThreeTable();	
	
        t.insert();
		t.upload();
		t.detele();

        // 把数据插入两张表
		t.insertTwoTable();

	}

	public void testArrayHandler() {

		ResultSetHandler<Object[]> rsh = new ArrayHandler();
		QueryRunner qr = new QueryRunner(new DBConnection());

		String sql = "select * from student, book where student.book_id = book.book_id";
		try {
			Object[] arr = qr.query(sql, rsh);
			for (int i = 0; i < arr.length; i++)
				System.out.print(arr[i].toString() + "\t");
			System.out.println("");
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void testArrayListHandler() {

		ResultSetHandler<List<Object[]>> rsh = new ArrayListHandler();
		QueryRunner qr = new QueryRunner(new DBConnection());

		String sql = "select * from student, book where student.book_id = book.book_id";

		try {
			List<Object[]> list = qr.query(sql, rsh);
			int size = list.size();
			for (int i = 0; i < size; i++) {
				Object[] arr = list.get(i);
				for (int j = 0; j < arr.length; j++)
					System.out.print(arr[j].toString() + "\t");
				System.out.println("");
			}
			System.out.println("");
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void testBeanHandler() {

		ResultSetHandler<Student> rsh = new BeanHandler<Student>(Student.class);
		QueryRunner qr = new QueryRunner(new DBConnection());

		String sql = "select * from student, book where student.book_id = book.book_id";

		try {
			Student student = qr.query(sql, rsh);
			System.out.print(student.getStudent_id() + "\t");
			System.out.print(student.getStudent_name() + "\t");
			System.out.print(student.getStudent_age() + "\t");
			System.out.print(student.getStudent_email() + "\n");

		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void queryTwoTable() {

		QueryRunner qr = new QueryRunner(new DBConnection());

		String sql = "select * from student, book where student.book_id = book.book_id";

		try {
			Student student = qr.query(sql, new ResultSetHandler<Student>() {

				public Student handle(ResultSet rs) throws SQLException {
					Student student = null;
					if (rs.next()) {
						BeanProcessor bp = new BeanProcessor();
						student = bp.toBean(rs, Student.class);
						Book book = bp.toBean(rs, Book.class);
						student.setBook(book);
					}
					return student;
				}
			});

			System.out.print(student.getStudent_id() + "\t");
			System.out.print(student.getStudent_name() + "\t");
			System.out.print(student.getStudent_age() + "\t");
			System.out.print(student.getStudent_email() + "\t");

			System.out.print(student.getBook().getBook_id() + "\t");
			System.out.print(student.getBook().getBook_name() + "\t");
			System.out.print(student.getBook().getBook_price() + "\n");

		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void testBeanListHandler() {

		ResultSetHandler<List<Student>> rsh = new BeanListHandler<Student>(Student.class);
		QueryRunner qr = new QueryRunner(new DBConnection());

		String sql = "select * from student, book where student.book_id = book.book_id";

		try {
			List<Student> list = qr.query(sql, rsh);
			int size = list.size();
			for (int i = 0; i < size; i++) {
				Student student = list.get(i);
				System.out.print(student.getStudent_id() + "\t");
				System.out.print(student.getStudent_name() + "\t");
				System.out.print(student.getStudent_age() + "\t");
				System.out.print(student.getStudent_email() + "\n");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void queryListTwoTable() {

		QueryRunner qr = new QueryRunner(new DBConnection());

		String sql = "select * from student, book where student.book_id = book.book_id";

		try {

			List<Student> list = qr.query(sql,
					new ResultSetHandler<List<Student>>() {

						public List<Student> handle(ResultSet rs) throws SQLException {
							List<Student> list = new ArrayList<Student>();
							BeanProcessor bp = new BeanProcessor();
							while (rs.next()) {

								Student student = bp.toBean(rs, Student.class);
								Book book = bp.toBean(rs, Book.class);
								student.setBook(book);
								list.add(student);
							}
							return list;
						}

					});

			if (list != null && !list.isEmpty()) {
				for (Student student : list) {
					System.out.print(student.getStudent_id() + "\t");
					System.out.print(student.getStudent_name() + "\t");
					System.out.print(student.getStudent_age() + "\t");
					System.out.print(student.getStudent_email() + "\t");

					System.out.print(student.getBook().getBook_id() + "\t");
					System.out.print(student.getBook().getBook_name() + "\t");
					System.out.print(student.getBook().getBook_price() + "\n");
				}
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void queryListThreeTable() {

		Connection conn = null;
		QueryRunner qr = new QueryRunner();
		
		List<School> schoolList = null;
		try {

			conn = new DBConnection().getConnection();
			String sql = "select * from school";
			schoolList = qr.query(conn, sql, new BeanListHandler<School>(School.class));

			if (schoolList != null && !schoolList.isEmpty()) {
				for (School school : schoolList) {
					sql = "select * from student, book where student.book_id = book.book_id and student.school_id = ?";
					ResultSetHandler<List<Student>> rsh = new ResultSetHandler<List<Student>>() {

						public List<Student> handle(ResultSet rs) throws SQLException {

							List<Student> list = new ArrayList<Student>();
							BeanProcessor bp = new BeanProcessor();
							while (rs.next()) {

								Student student = bp.toBean(rs, Student.class);
								Book book = bp.toBean(rs, Book.class);
								student.setBook(book);
								list.add(student);
							}
							return list;
						}

					};
					List<Student> studentList = qr.query(conn, sql, rsh, school.getSchool_id());
					school.setStudentList(studentList);
				}

			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
		
		if (schoolList != null && !schoolList.isEmpty()) {
			for (School school : schoolList) {
				System.out.print(school.getSchool_id() + "\t");
				System.out.print(school.getSchool_name() + "\t");
				System.out.print(school.getSchool_address() + "\n");
				for (Student student : school.getStudentList()) {
					System.out.print("\t" + student.getStudent_id() + "\t");
					System.out.print(student.getStudent_name() + "\t");
					System.out.print(student.getStudent_age() + "\t");
					System.out.print(student.getStudent_email() + "\t");

					System.out.print(student.getBook().getBook_id() + "\t");
					System.out.print(student.getBook().getBook_name() + "\t");
					System.out.print(student.getBook().getBook_price() + "\n");
				}
			}

		}

	}

	public void insert() {

		QueryRunner qr = new QueryRunner(new DBConnection());

		String sql = "insert into student values(?, ?, ?, ?)";
		Object[] params = new Object[] { "seven", 23, "seven123@qq.com", 1 };

		try {
			System.out.println(qr.update(sql, params));
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void insertTwoTable() {

		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try {
			conn = new DBConnection().getConnection();
			QueryRunner qr = new QueryRunner();

			conn.setAutoCommit(false);

			String sql = "insert into book values(?, ?)";
			Object[] params = new Object[] { "C#", 99.36 };

			pst = conn.prepareStatement(sql,
					PreparedStatement.RETURN_GENERATED_KEYS);
			qr.fillStatement(pst, params);
			pst.execute();
			rs = pst.getGeneratedKeys();
			int book_id = rs.next() ? rs.getInt(1) : 0;

			sql = "insert into student values(?, ?, ?, ?)";
			params = new Object[] { "seven", 23, "seven123@qq.com", book_id };

			pst = conn.prepareStatement(sql);
			qr.fillStatement(pst, params);
			pst.execute();

			conn.commit();

		} catch (SQLException e) {
			try {
				DbUtils.rollback(conn);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn, pst, rs);
		}

	}

	public void upload() {

		QueryRunner qr = new QueryRunner(new DBConnection());

		String sql = "update student set student_name = ? where student_id = ?";
		Object[] params = new Object[] { "seven+++", 11 };

		try {
			System.out.println(qr.update(sql, params));
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void detele() {

		QueryRunner qr = new QueryRunner(new DBConnection());

		String sql = "delete from student where student_id = ?";
		Object[] params = new Object[] { 11 };

		try {
			System.out.println(qr.update(sql, params));
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}



这张是t.queryListThreeTable()的查询效果


这张是t.queryListTwoTable()的查询效果


这张是t.queryTwoTable()的查询效果



最后附上示例代码
  • 大小: 35 KB
  • 大小: 17.7 KB
  • 大小: 16.2 KB
  • 大小: 8.1 KB
  • 大小: 27.8 KB
   发表时间:2011-06-04  
和楼主一样,我也是最近才看的,写的不错
0 请登录后投票
   发表时间:2011-06-05  
不容易有个人顶了一下
0 请登录后投票
   发表时间:2011-06-16  
楼主有没有对dbutils再进行封装的代码,类似spring 的hibernateTemplate
0 请登录后投票
   发表时间:2011-06-17  
hzl7652 写道
楼主有没有对dbutils再进行封装的代码,类似spring 的hibernateTemplate


没有,我个人更喜欢Mybatis
0 请登录后投票
   发表时间:2011-11-07  
kanny87929 写道
hzl7652 写道
楼主有没有对dbutils再进行封装的代码,类似spring 的hibernateTemplate


没有,我个人更喜欢Mybatis


mybatis可以动态拼sql,而且是放在一个xml中,与代码解耦。做数据库迁移也很方便,感觉还是mybatis到位一些!
0 请登录后投票
   发表时间:2011-12-05  
非常好!学习啦!
还有一个问题:
select name ,count(name) from student groub by name;
类似这样的集合函数的查询如何实现呢?
0 请登录后投票
   发表时间:2011-12-05  
以前知道这个东西,感觉还可以,但是像这种小的东西,自己可以试着写一个,特别是要写一个通用类出来,比如说用泛型写个通用类
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics