commons-dbutils 是 Apache 组织提供的一个开源JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。因此dbutils成为很多不喜欢hibernate的公司的首选。
DbUtils组件的主要作用是简化jdbc操作。
项目准备
1. 引入mysql驱动:mysql-connector-java-5.1.38-bin.jar
2. 引入jar文件 : commons-dbutils-1.6.jar
下载dbutils组件: http://commons.apache.org/proper/commons-dbutils/download_dbutils.cgi
QueryRunner类,位于org.apache.commons.dbutils包下,全名org.apache.commons.dbutils.QueryRunner
QueryRunner类是组件的核心工具类:定义了所有的与数据库操作的方法(查询、更新)
【Executes SQL queries】 with 【pluggable strategies】 for 【handling ResultSets】.
QueryRunner类提供了默认的构造函数:public QueryRunner() ,在进行update、query等方式法需要传入Connection对象
QueryRunner类还提供了另外一个构造函数,接受DataSource类型的对象:public QueryRunner(DataSource ds)
(1)public int update(Connection conn, String sql)
//描述:Execute an SQL INSERT, UPDATE, or DELETE query without replacement parameters.
(2)public int update(Connection conn, String sql, Object param)
//描述:Execute an SQL INSERT, UPDATE, or DELETE query with a single replacement parameter.
(3)public int update(Connection conn, String sql, Object... params)
//描述:Execute an SQL INSERT, UPDATE, or DELETE query.
(1)public int update(String sql)
(2)public int update(String sql, Object param)
(3)public int update(String sql, Object... params)
(1)public <T> T query(Connection conn, String sql, ResultSetHandler<T> rsh)
(2)public <T> T query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params)
(1)public <T> T query(String sql, ResultSetHandler<T> rsh)
(2)public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)
2.使用BeanHandler、BeanListHandler和ScalarHandler
DbUtils类,位于org.apache.commons.dbutils包下,全名org.apache.commons.dbutils.DbUtils