1. Dbutils Overview
Dbutils is a simplified SDK for JDBC. Use dbutils to import jar packages: Commons-dbutils-1.4.jar
Core class: Queryrunner
Package Org.apache.commons.dbutils
Java.lang.Object
|--org.apache.commons.dbutils.abstractqueryrunner
|--org.apache.commons.dbutils.queryrunner
Construction Method:
Queryrunner (DataSource DS), receive data sources, can be obtained using tools such as DBCP,C3P0.
Common APIs:
1. Enquiry
<T> T query (String sql, resultsethandler<t> rsh, Object ... params)
Executes a query statement encapsulated in SQL, the SQL statement takes a preprocessing object parameter form, passes the parameters in the SQL statement through the params, and returns the result object, depending on the implementation class passed into the Resultsethandler, the resulting object can be either a collection of objects or a single object
<T> T Query (Connection conn, String sql, resultsethandler<t> rsh, Object ... params)
This method allows the caller to control the access and shutdown of the connection and to open a transaction at the same time.
2. Update
int update (String sql, Object ... params)
You can insert, UPDATE, Delete, and so on. Returns the number of data bars that are affected.
int update (Connection conn, String sql, Object ... params)
This method allows the caller to control the access and shutdown of the connection and to open a transaction at the same time.
3. About result set processing
Interface resultsethandler<t>
T is the target object type that will be converted to the result set as input.
T handle (ResultSet RS) This method receives the query result ResultSet of the SQL statement and transforms the result set into a concrete type of object
Three common implementation classes of Resultsethandler
A.beanhandler<t>
Construction method: Beanhandler (class<t> type)
Type is the byte code that will javabean the target
Implementation method: T handle (ResultSet RS)
A target class is constructed using the type bytecode JavaBean object, and the contents of the record of the first row of the resulting set of the query are encapsulated in the object, returned as a return value to the caller query, and returned as the result of query.
B.beanlisthandler<t>
Similar to Beanhandler, it is simply a list collection that returns the target class JavaBean.
C.scalarhandler
This class is used to handle the use of aggregate functions in query statements, and when a Scalarhandler object is created using the parameterless constructor, its handle method returns the contents of the first column of the query results.
Dbutils Tool Class
The Dbutils tool class provides a number of ways to handle transactions, such as handling exceptions.
static void Commitandclose (Connection conn) throws SqlException commits and closes if an exception is thrown
Static commitandclosequietly (Connection conn) commits and closes if there is an exception that does not do any processing
Static Rollbackandclose (Connection conn) throws SQLException rollback and close If an exception is thrown
Static rollbackandclosequietly (Connection conn) rollback and close if there is an exception that does not do any processing
2.Demo Demo
Using dbutils combined with C3P0, the database was separately deleted and changed, and the usage of each API was demonstrated.
The structure of the JavaBean is as follows, overriding the ToString method for demonstration purposes, with the same database table structure as the bean.
1 Public classUser {2 Private intID;3 PrivateString name;4 Public intgetId () {5 returnID;6 }7 Public voidSetId (intID) {8 This. ID =ID;9 }Ten PublicString GetName () { One returnname; A } - Public voidsetName (String name) { - This. Name =name; the } - @Override - PublicString toString () { - return"User [id=" + ID + ", name=" + name + "]"; + } -}
The operation of the database is as follows: (c3p0 to get data source omitted)
1 Packagecom.itheima.dbutils;2 3 Importjava.sql.SQLException;4 Importjava.util.List;5 6 ImportOrg.apache.commons.dbutils.QueryRunner;7 ImportOrg.apache.commons.dbutils.handlers.BeanHandler;8 ImportOrg.apache.commons.dbutils.handlers.BeanListHandler;9 ImportOrg.apache.commons.dbutils.handlers.ScalarHandler;Ten Importorg.junit.Test; One A Public classDbutilsdemo { -Queryrunner runner =NewQueryrunner (C3p0utils.getdatasource ()); - @Test the Public voidAdd () { - Try { -String sql = "INSERT into T_user (name) VALUES (?)"; -Object[] params = {"White"}; + intR =runner.update (sql,params); - System.out.println (r); +}Catch(SQLException e) { A Throw NewRuntimeException (e); at } - } - @Test - Public voidDelete () { - Try { -String sql = "Delete from T_user where id=?"; inObject[] params = {4}; - intR =runner.update (sql,params); to System.out.println (r); +}Catch(SQLException e) { - Throw NewRuntimeException (e); the } * } $ @TestPanax Notoginseng Public voidUpdate () { - Try { theString sql = "Update t_user set name=?" where id=? "; +Object[] params = {"Jane", 2}; A intR =runner.update (sql,params); the System.out.println (r); +}Catch(SQLException e) { - Throw NewRuntimeException (e); $ } $ } - @Test - Public voidSelect1 () { the Try { -String sql = "SELECT * from T_user where id=?";WuyiObject[] params = {2}; theUser user= runner.query (SQL,NewBeanhandler<user> (User.class), params); - System.out.println (user); Wu}Catch(SQLException e) { - Throw NewRuntimeException (e); About } $ } - @Test - Public voidSelect2 () { - Try { AString sql = "SELECT * FROM T_user"; +Object[] params = {}; thelist<user> userlist= runner.query (SQL,NewBeanlisthandler<user> (User.class), params); - for(User user:userlist) $ System.out.println (user); the}Catch(SQLException e) { the Throw NewRuntimeException (e); the } the } - @Test in Public voidselect3 () { the Try { theString sql = "SELECT COUNT (*) from T_user"; AboutObject[] params = {}; theLong count= (long) runner.query (SQL,NewScalarhandler (), params); the System.out.println (count); the}Catch(SQLException e) { + Throw NewRuntimeException (e); - } the }Bayi}
Database Tools--dbutils Use of tool classes