DBUtils
commons-dbutils is an open source JDBC tool library provided by the Apache organization, which encapsulates the addition, deletion, modification, and query operations for the database
API
- QueryRunner
- ResulSetHandler
- Dbutils
Insert example
Connection conn = null;
try {
QueryRunner runner = new QueryRunner();
conn = JBBCUtils.getConnections3();
String sql = "insert into customers(name,emial,birth) values(?,?,?)";
int insertCount = runner.update(conn,sql,"蔡旭坤","[email protected]","1993-03-01");
System.out.println(insertCount);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.closeResource(conn,null);
}
Update
public static void main(String[] args) {
Connection conn = null;
try {
QueryRunner runner = new QueryRunner();
conn = JBBCUtils.getConnections3();
String sql = "select id,name,email,birth from customers where id < ?";
BeanListHandler<Customer> handler = new BeanListHandler<Cunstomer>(customer.class);
List<Customer> query = runner.query(conn.sql, handler, 23);
System.out.println(insertCount);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.closeResource(conn,null);
}
}
Special values in the lookup table
public static void main(String[] args) {
Connection conn = null;
try {
QueryRunner runner = new QueryRunner();
conn = JBBCUtils.getConnections3();
String sql = "select count(*) from customers";
ScalarHandler handler = new ScalarHandler();
Long count = (Long)runner.query(conn.sql, handler);
System.out.println(count);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.closeResource(conn,null);
}
}
Custom ResultSetHandler
public static void main(String[] args) {
Connection conn = null;
try {
QueryRunner runner = new QueryRunner();
conn = JBBCUtils.getConnections3();
String sql = "select id,name,email,birth from customers where id = ?";
ResultSetHandler<Customers> resultSetHandler = new ResultSetHandler<Customers>() {
@Override
public Customers handle(ResultSet rs) throws SQLException {
if(resultSet.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String email = rs.getString(3);
Date birth = rs.getDate(4);
Customer customer = new Cunstomer(id,name,email,birth);
return customer;
}
return null;
}
};
Long count = (Long)runner.query(conn.sql, handler);
System.out.println(count);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.closeResource(conn,null);
}
}