今天把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
分享到:
相关推荐
这个文件很可能是DbUtils的使用示例代码,可能包含了连接数据库、执行查询、更新数据等操作。通过阅读并运行这个示例,你可以更好地理解DbUtils的用法和优势。 总结起来,Apache DbUtils是JDBC编程的利器,它通过...
使用 Commons dbutils 可以极大地简化 JDBC 编程,避免了许多手动处理连接、声明和结果集的工作,同时也提高了代码的可读性和可维护性。例如,使用 `QueryRunner` 执行查询和更新操作时,只需要提供 SQL 语句、参数...
# 使用示例 db = MyDatabase() conn = db.get_connection() cursor = conn.cursor() cursor.execute("SELECT * FROM mytable") rows = cursor.fetchall() ``` 在以上代码中,`PooledDB` 创建了一个连接池,每次需要...
以下是一个简单的示例,展示了如何使用 DBUtils 进行数据库操作: ```java import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons....
DbUtils封装了对JDBC的操作,简化了JDBC操作,可以少写代码。 应用实践小结: 一、cn.fansunion.dbutils.example,5个独立的例子。 1.AsyncUpdateExample.java,演示如何执行异步更新。 2.BeanHandlerExample....
6. **PreparedStatement的使用**:DBUtils鼓励使用PreparedStatement来防止SQL注入攻击,它能自动处理参数绑定,提高代码的可读性和安全性。 关于SQLite,它是一个开源、轻量级的嵌入式关系数据库,广泛应用于移动...
**示例代码** 以下是一个简单的DBUtils使用示例,展示如何执行一个查询并处理结果: ```java import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org....
示例代码中没有直接展示SQL参数化,但在实际应用中,使用QueryRunner进行查询时,通常会用占位符(如`?`)和数组参数来避免SQL注入攻击。例如,`qRunner.query(conn, "SELECT * FROM table WHERE id=?", new Object...
DbUtils是一个在Java开发中广泛...4. 示例代码或帮助文档:可能包含一些示例程序或用户指南,帮助初学者快速上手。 通过这些文件,开发者可以轻松地将DbUtils集成到自己的项目中,充分利用其优势,简化数据库操作。
三、DBUtils的使用示例 1. 获取数据库连接: ```java BasicDataSource ds = new BasicDataSource(); ds.setUrl("jdbc:mysql://localhost:3306/test"); ds.setUsername("root"); ds.setPassword("password"); ...
**使用示例** 以下是一个基本的使用`dbutils` 查询数据库的例子: ```java import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons....
以下是一个简单的示例,展示了如何在Java程序中使用C3P0和DBUtils: ```java import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons....
**dbutils** 是一个 Apache Commons 项目,它提供了一个...对于初学者和经验丰富的开发者来说,理解并使用 dbutils 都能提高开发效率和代码质量。通过查看源码,我们还能深入了解 Java JDBC 操作的最佳实践和设计模式。
这个版本可能包含了DbUtils的二进制(bin)和源代码(src)两个部分,分别对应于"commons-dbutils-1.7-bin.zip"和"commons-dbutils-1.7-src.zip"这两个文件。 DbUtils的主要功能是作为一个数据库访问的辅助工具,它...
在`commons-dbutils-1.6-src`中,你可以看到DBUtils的源代码,通过阅读源码,你可以深入理解其内部机制,包括异常处理策略、连接池的使用、结果集的处理流程等。这对于定制自己的数据库访问工具或者学习数据库操作的...
`st.rar`可能是一个自定义的解决方案或示例代码,而`DBUtils-1.0.zip`则可能是dbutils库的一个早期版本。解压并研究这些文件,我们可以深入理解如何在不同场景下配置和使用dbutils库。 在实际应用中,使用dbutils和...
commons-dbutils的再封装jar包,Blog文件的示例代码
示例代码: ```java // 创建 QueryRunner 实例 QueryRunner runner = new QueryRunner(); // 开启事务 DbUtils.startTransaction(); try { // 执行插入操作 int rowsAffected = runner.update(conn, "INSERT ...
接着,可以通过以下代码示例了解如何使用DBUtils执行SQL查询和更新操作: ```java import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache....
4. **示例代码** - 查询操作: ```java QueryRunner runner = new QueryRunner(dataSource); String sql = "SELECT * FROM users WHERE id = ?"; User user = runner.query(sql, new BeanHandler(User.class), ...