简单JDBC框架——DBUtils
2013-07-26 21:30
459 查看
1、元数据- DataBaseMetaData
(1)元数据:数据库、表、列的定义信息。
(2)Connection.getMetaData()
(3)DataBaseMetaData对象
getURL():返回一个String类对象,代表数据库的URL。
getUserName():返回连接当前数据库管理系统的用户名。
getDriverName():返回驱动驱动程序的名称。
getPrimaryKeys(String catalog, String schema, String table):返回指定表主键的结果集
getTables()
(4)原来由jdbcUtil创建连接,现在由dataSource创建连接,为实现不和具体数据为绑定,因此datasource也应采用配置文件的方法获得连接。
public void test1(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = dataSource.getConnection();
DatabaseMetaData databaseMetaData = conn.getMetaData();
System.out.println(databaseMetaData.getURL());
System.out.println(databaseMetaData.getUserName());
System.out.println(databaseMetaData.getDriverName());
rs = databaseMetaData.getPrimaryKeys(null, null, "account");
while(rs.next()){
short seq = rs.getShort("KEY_SEQ");
String name = rs.getString("COLUMN_NAME");
System.out.println(seq+":"+name);
}
rs = databaseMetaData.getTables(null, null, "ac%", new String []{"TABLE"});
while(rs.next()){
String tab_name = rs.getString("TABLE_NAME");
System.out.println(tab_name);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs = null;
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ps = null;
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn = null;
}
}
}
}
2、元数据- ParameterMetaData
(1)PreparedStatement . getParameterMetaData()
获得代表PreparedStatement元数据的ParameterMetaData对象。
Select * from user where name=? And password=?
(2)ParameterMetaData对象
getParameterCount()
获得指定参数的个数
getParameterTypeName(int param)
获得指定参数的sql类型
(3)getParameterType异常处理
Parameter metadata not available for the given statement
(4)url后面拼接参数
?generateSimpleParameterMetadata=true
/**
* 参数元数据
*/
@Test
public void test2(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = dataSource.getConnection();
ps = conn.prepareStatement("select * from account where id=? and name=?");
ParameterMetaData metaData = ps.getParameterMetaData();
System.out.println(metaData.getParameterCount());
}catch (Exception e) {
e.printStackTrace();
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs = null;
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ps = null;
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn = null;
}
}
}
}
3、元数据- ResultSetMetaData
(1)ResultSet. getMetaData()
获得代表ResultSet对象元数据的ResultSetMetaData对象。
(2)ResultSetMetaData对象
getColumnCount()
返回resultset对象的列数
getColumnName(int column)
获得指定列的名称
getColumnTypeName(int column)
获得指定列的类型
public void test3(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = dataSource.getConnection();
ps = conn.prepareStatement("select * from account");
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
System.out.println("-----------------------------------");
for(int i=1;i<=metaData.getColumnCount();i++){
System.out.print(metaData.getColumnName(i)+":"+metaData.getColumnTypeName(i)+"\t");
}
System.out.println();
System.out.println("-----------------------------------");
while(rs.next()){
System.out.print(rs.getInt("id")+"\t\t");
System.out.print(rs.getString("name")+"\t\t");
System.out.print(rs.getDouble("money")+"\t\t");
System.out.println();
}
System.out.println("-----------------------------------");
}catch (Exception e) {
e.printStackTrace();
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs = null;
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ps = null;
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn = null;
}
}
}
}
}
4、Apache—DBUtils框架简介
(1)commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。因此dbutils成为很多不喜欢hibernate的公司的首选。
(2)API介绍:
org.apache.commons.dbutils.QueryRunner --- 核心
org.apache.commons.dbutils.ResultSetHandler
工具类
org.apache.commons.dbutils.DbUtils、。
5、DbUtils类
DbUtils :提供如关闭连接、装载JDBC驱动程序等常规工作的工具类,里面的所有方法都是静态的。主要方法如下:
public static void close(…) throws java.sql.SQLException: DbUtils类提供了三个重载的关闭方法。这些方法检查所提供的参数是不是NULL,如果不是的话,它们就关闭Connection、Statement和ResultSet。
public static void closeQuietly(…): 这一类方法不仅能在Connection、Statement和ResultSet为NULL情况下避免关闭,还能隐藏一些在程序中抛出的SQLException。
public static void commitAndCloseQuietly(Connection conn): 用来提交连接,然后关闭连接,并且在关闭连接时不抛出SQL异常。
public static boolean loadDriver(java.lang.String driverClassName):这一方装载并注册JDBC驱动程序,如果成功就返回true。使用该方法,你不需要捕捉这个异常ClassNotFoundException。
6、QueryRunner类
(1)该类简单化了SQL查询,它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作,能够大大减少编码量。
(2)QueryRunner类提供了两个构造方法:
默认的构造方法
需要一个 javax.sql.DataSource 来作参数的构造方法。
7、QueryRunner类的主要方法
(1)更新操作
public int update(Connection conn, String sql, Object... params)
public int update(String sql, Object... params)
(2)查询操作
public Object query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params)
public Object query(String sql, ResultSetHandler<T> rsh, Object... params)
package com.itheima.dbutils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class update {
@Test
public void test5() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
runner.update("delete from account where name=?","d");
}
@Test
public void test4() throws SQLException{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
QueryRunner runner = new QueryRunner();
runner.update(conn,"insert into account values(null,?,?)","d",9999);
conn.commit();
}
//MyDbUtils实现update操作
@Test
public void test3() throws SQLException{
MyQueryRunner runner = new MyQueryRunner(new ComboPooledDataSource());
runner.update("update account set money=2000 where name=?", "b");
}
//DbUtils框架实现update操作
@Test
public void test2() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
//runner.update("update account set money=1000 where name=?", "a");
runner.update("update orders set price=1000 where product=? and id=? ","电视",1);
}
//传统方式实现update操作
@Test
public void test1(){
DataSource dataSource = new ComboPooledDataSource();
Connection conn = null;
PreparedStatement ps = null;
try{
conn = dataSource.getConnection();
ps = conn.prepareStatement("update account set money=2000 where name=?");
ps.setString(1, "a");
ps.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}finally{
DbUtils.closeQuietly(conn, ps, null);
}
}
}
8、ResultSetHandler接口
(1)该接口用于处理 java.sql.ResultSet,将数据按要求转换为另一种形式。
(2)ResultSetHandler 接口提供了一个单独的方法:Object handle (java.sql.ResultSet .rs)。
package com.itheima.dbutils;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
public class MyQueryRunner {
private DataSource source;
public MyQueryRunner() {
}
public MyQueryRunner(DataSource source) {
this.source = source;
}
public int update(String sql,Object ...args) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
try{
//获取连接、获取传输器
conn = source.getConnection();
ps = conn.prepareStatement(sql);
//获取参数元数据,根据参数的数量循环赋值
ParameterMetaData metaData = ps.getParameterMetaData();
for(int i = 1;i<=metaData.getParameterCount();i++){
ps.setObject(i, args[i-1]);
}
return ps.executeUpdate();
}finally{
DbUtils.closeQuietly(conn, ps, null);
}
}
public <T> T query(String sql,MyResultSetHandler<T> handler,Object ...args) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
//获取连接、获取传输器
conn = source.getConnection();
ps = conn.prepareStatement(sql);
//获取参数元数据,根据参数的数量循环赋值
ParameterMetaData metaData = ps.getParameterMetaData();
for(int i = 1;i<=metaData.getParameterCount();i++)
{
ps.setObject(i, args[i-1]);
}
rs = ps.executeQuery();
return handler.handle(rs);
}finally{
DbUtils.closeQuietly(conn, ps, null);
}
}
}
package com.itheima.dbutils;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface MyResultSetHandler<T> {
public T handle(ResultSet rs) throws SQLException;
}
package com.itheima.dbutils;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.junit.Test;
import com.itheima.domain.Account;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class query {
//MyDbUtils实现查询
@Test
public void test2() throws SQLException{
MyQueryRunner runner = new MyQueryRunner(new ComboPooledDataSource());
Account account = runner.query("select * from orders where id=?", new MyResultSetHandler<Account>(){
public Account handle(ResultSet rs) throws SQLException {
Account account = null;
if(rs.next()){
account = new Account();
account.setId(rs.getInt("id"));
account.setProduct(rs.getString("product"));
account.setPrice(rs.getDouble("price"));
}
return account;
}
}, 4);
System.out.println(account.getProduct());
}
//DBUTILS实现查询
// @Test
// public void test1() throws SQLException{
// QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
// Account account = runner.query("select * from account where name=?", new ResultSetHandler<Account>(){
//
// public Account handle(ResultSet rs) throws SQLException {
// Account account = null;
// if(rs.next()){
// account = new Account();
// account.setId(rs.getInt("id"));
// account.setName(rs.getString("name"));
// account.setMoney(rs.getDouble("money"));
// }
// return account;
// }
// }, "a");
// System.out.println(account.getName());
// }
}
9、ResultSetHandler 接口的实现类
(1)ArrayHandler:把结果集中的第一行数据转成对象数组。
//ArrayHandler:将查询结果中的第一行数据封装为一个数组返回
@Test
public void test1() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
Object[] objs = runner.query("select * from account", new ArrayHandler());
System.out.println(objs);
}
(2)ArrayListHandler:把结果集中的每一行数据都转成一个对象数组,再存放到List中。
//ArrayListHandler:将查询结果的每一行封装为一个数组,再将数组组成一个List返回
@Test
public void test2() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
List<Object[]> list = runner.query("select * from account", new ArrayListHandler());
System.out.println(list);
}
(3)BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
//BeanHandler:将结果集中的第一行数据封装为JavaBean返回
@Test
public void test3() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
Account account = runner.query("select * from account", new BeanHandler<Account>(Account.class));
System.out.println(account.getProduct());
}
(4)BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
//BeanListHandler:将结果集中的每一行数据封装为JavaBean组成List返回
@Test
public void test4() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
List<Account> list = runner.query("select * from account", new BeanListHandler<Account>(Account.class));
System.out.println(list);
}
(5)MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
//MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
@Test
public void test5() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
Map<String, Object> map = runner.query("select * from account", new MapHandler());
System.out.println(map);
}
(6)MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
//MapListHandler:将结果集中的每一行数据封装到一个Map里,key是列名,value就是对应的值,所有的map组成一个List返回。
@Test
public void test6() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
List<Map<String, Object>> list= runner.query("select * from account", new MapListHandler());
System.out.println(list);
}
(7)ColumnListHandler:将结果集中某一列的数据存放到List中。
//ColumnListHandler:将结果集中某一列的数据存放到List中。
@Test
public void test7() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
List<Object>list = runner.query("select * from account", new ColumnListHandler());
System.out.println(list);
}
(8)KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里(List<Map>),再把这些map再存到一个map里,其key为指定的列。
//KeyedHandler:将结果集中的每一行数据都封装到一个Map里(List<Map>),再把这些map再存到一个map里,其key为指定的列
@Test
public void test8() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
Map<Object, Map<String, Object>> map= runner.query("select * from account", new KeyedHandler("id"));
System.out.println(map);
}
(9)Long long = (Long)queryRunner.query("select count(*) from account",new ScalarHandler(1));//进行单值查询。。。。。。
public void test9() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
long count = (Long)runner.query("select count(*) from account", new ScalarHandler());
System.out.println(count);
}
(1)元数据:数据库、表、列的定义信息。
(2)Connection.getMetaData()
(3)DataBaseMetaData对象
getURL():返回一个String类对象,代表数据库的URL。
getUserName():返回连接当前数据库管理系统的用户名。
getDriverName():返回驱动驱动程序的名称。
getPrimaryKeys(String catalog, String schema, String table):返回指定表主键的结果集
getTables()
(4)原来由jdbcUtil创建连接,现在由dataSource创建连接,为实现不和具体数据为绑定,因此datasource也应采用配置文件的方法获得连接。
public void test1(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = dataSource.getConnection();
DatabaseMetaData databaseMetaData = conn.getMetaData();
System.out.println(databaseMetaData.getURL());
System.out.println(databaseMetaData.getUserName());
System.out.println(databaseMetaData.getDriverName());
rs = databaseMetaData.getPrimaryKeys(null, null, "account");
while(rs.next()){
short seq = rs.getShort("KEY_SEQ");
String name = rs.getString("COLUMN_NAME");
System.out.println(seq+":"+name);
}
rs = databaseMetaData.getTables(null, null, "ac%", new String []{"TABLE"});
while(rs.next()){
String tab_name = rs.getString("TABLE_NAME");
System.out.println(tab_name);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs = null;
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ps = null;
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn = null;
}
}
}
}
2、元数据- ParameterMetaData
(1)PreparedStatement . getParameterMetaData()
获得代表PreparedStatement元数据的ParameterMetaData对象。
Select * from user where name=? And password=?
(2)ParameterMetaData对象
getParameterCount()
获得指定参数的个数
getParameterTypeName(int param)
获得指定参数的sql类型
(3)getParameterType异常处理
Parameter metadata not available for the given statement
(4)url后面拼接参数
?generateSimpleParameterMetadata=true
/**
* 参数元数据
*/
@Test
public void test2(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = dataSource.getConnection();
ps = conn.prepareStatement("select * from account where id=? and name=?");
ParameterMetaData metaData = ps.getParameterMetaData();
System.out.println(metaData.getParameterCount());
}catch (Exception e) {
e.printStackTrace();
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs = null;
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ps = null;
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn = null;
}
}
}
}
3、元数据- ResultSetMetaData
(1)ResultSet. getMetaData()
获得代表ResultSet对象元数据的ResultSetMetaData对象。
(2)ResultSetMetaData对象
getColumnCount()
返回resultset对象的列数
getColumnName(int column)
获得指定列的名称
getColumnTypeName(int column)
获得指定列的类型
public void test3(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = dataSource.getConnection();
ps = conn.prepareStatement("select * from account");
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
System.out.println("-----------------------------------");
for(int i=1;i<=metaData.getColumnCount();i++){
System.out.print(metaData.getColumnName(i)+":"+metaData.getColumnTypeName(i)+"\t");
}
System.out.println();
System.out.println("-----------------------------------");
while(rs.next()){
System.out.print(rs.getInt("id")+"\t\t");
System.out.print(rs.getString("name")+"\t\t");
System.out.print(rs.getDouble("money")+"\t\t");
System.out.println();
}
System.out.println("-----------------------------------");
}catch (Exception e) {
e.printStackTrace();
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs = null;
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ps = null;
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn = null;
}
}
}
}
}
4、Apache—DBUtils框架简介
(1)commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。因此dbutils成为很多不喜欢hibernate的公司的首选。
(2)API介绍:
org.apache.commons.dbutils.QueryRunner --- 核心
org.apache.commons.dbutils.ResultSetHandler
工具类
org.apache.commons.dbutils.DbUtils、。
5、DbUtils类
DbUtils :提供如关闭连接、装载JDBC驱动程序等常规工作的工具类,里面的所有方法都是静态的。主要方法如下:
public static void close(…) throws java.sql.SQLException: DbUtils类提供了三个重载的关闭方法。这些方法检查所提供的参数是不是NULL,如果不是的话,它们就关闭Connection、Statement和ResultSet。
public static void closeQuietly(…): 这一类方法不仅能在Connection、Statement和ResultSet为NULL情况下避免关闭,还能隐藏一些在程序中抛出的SQLException。
public static void commitAndCloseQuietly(Connection conn): 用来提交连接,然后关闭连接,并且在关闭连接时不抛出SQL异常。
public static boolean loadDriver(java.lang.String driverClassName):这一方装载并注册JDBC驱动程序,如果成功就返回true。使用该方法,你不需要捕捉这个异常ClassNotFoundException。
6、QueryRunner类
(1)该类简单化了SQL查询,它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作,能够大大减少编码量。
(2)QueryRunner类提供了两个构造方法:
默认的构造方法
需要一个 javax.sql.DataSource 来作参数的构造方法。
7、QueryRunner类的主要方法
(1)更新操作
public int update(Connection conn, String sql, Object... params)
public int update(String sql, Object... params)
(2)查询操作
public Object query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params)
public Object query(String sql, ResultSetHandler<T> rsh, Object... params)
package com.itheima.dbutils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class update {
@Test
public void test5() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
runner.update("delete from account where name=?","d");
}
@Test
public void test4() throws SQLException{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
QueryRunner runner = new QueryRunner();
runner.update(conn,"insert into account values(null,?,?)","d",9999);
conn.commit();
}
//MyDbUtils实现update操作
@Test
public void test3() throws SQLException{
MyQueryRunner runner = new MyQueryRunner(new ComboPooledDataSource());
runner.update("update account set money=2000 where name=?", "b");
}
//DbUtils框架实现update操作
@Test
public void test2() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
//runner.update("update account set money=1000 where name=?", "a");
runner.update("update orders set price=1000 where product=? and id=? ","电视",1);
}
//传统方式实现update操作
@Test
public void test1(){
DataSource dataSource = new ComboPooledDataSource();
Connection conn = null;
PreparedStatement ps = null;
try{
conn = dataSource.getConnection();
ps = conn.prepareStatement("update account set money=2000 where name=?");
ps.setString(1, "a");
ps.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}finally{
DbUtils.closeQuietly(conn, ps, null);
}
}
}
8、ResultSetHandler接口
(1)该接口用于处理 java.sql.ResultSet,将数据按要求转换为另一种形式。
(2)ResultSetHandler 接口提供了一个单独的方法:Object handle (java.sql.ResultSet .rs)。
package com.itheima.dbutils;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
public class MyQueryRunner {
private DataSource source;
public MyQueryRunner() {
}
public MyQueryRunner(DataSource source) {
this.source = source;
}
public int update(String sql,Object ...args) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
try{
//获取连接、获取传输器
conn = source.getConnection();
ps = conn.prepareStatement(sql);
//获取参数元数据,根据参数的数量循环赋值
ParameterMetaData metaData = ps.getParameterMetaData();
for(int i = 1;i<=metaData.getParameterCount();i++){
ps.setObject(i, args[i-1]);
}
return ps.executeUpdate();
}finally{
DbUtils.closeQuietly(conn, ps, null);
}
}
public <T> T query(String sql,MyResultSetHandler<T> handler,Object ...args) throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
//获取连接、获取传输器
conn = source.getConnection();
ps = conn.prepareStatement(sql);
//获取参数元数据,根据参数的数量循环赋值
ParameterMetaData metaData = ps.getParameterMetaData();
for(int i = 1;i<=metaData.getParameterCount();i++)
{
ps.setObject(i, args[i-1]);
}
rs = ps.executeQuery();
return handler.handle(rs);
}finally{
DbUtils.closeQuietly(conn, ps, null);
}
}
}
package com.itheima.dbutils;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface MyResultSetHandler<T> {
public T handle(ResultSet rs) throws SQLException;
}
package com.itheima.dbutils;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.junit.Test;
import com.itheima.domain.Account;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class query {
//MyDbUtils实现查询
@Test
public void test2() throws SQLException{
MyQueryRunner runner = new MyQueryRunner(new ComboPooledDataSource());
Account account = runner.query("select * from orders where id=?", new MyResultSetHandler<Account>(){
public Account handle(ResultSet rs) throws SQLException {
Account account = null;
if(rs.next()){
account = new Account();
account.setId(rs.getInt("id"));
account.setProduct(rs.getString("product"));
account.setPrice(rs.getDouble("price"));
}
return account;
}
}, 4);
System.out.println(account.getProduct());
}
//DBUTILS实现查询
// @Test
// public void test1() throws SQLException{
// QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
// Account account = runner.query("select * from account where name=?", new ResultSetHandler<Account>(){
//
// public Account handle(ResultSet rs) throws SQLException {
// Account account = null;
// if(rs.next()){
// account = new Account();
// account.setId(rs.getInt("id"));
// account.setName(rs.getString("name"));
// account.setMoney(rs.getDouble("money"));
// }
// return account;
// }
// }, "a");
// System.out.println(account.getName());
// }
}
9、ResultSetHandler 接口的实现类
(1)ArrayHandler:把结果集中的第一行数据转成对象数组。
//ArrayHandler:将查询结果中的第一行数据封装为一个数组返回
@Test
public void test1() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
Object[] objs = runner.query("select * from account", new ArrayHandler());
System.out.println(objs);
}
(2)ArrayListHandler:把结果集中的每一行数据都转成一个对象数组,再存放到List中。
//ArrayListHandler:将查询结果的每一行封装为一个数组,再将数组组成一个List返回
@Test
public void test2() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
List<Object[]> list = runner.query("select * from account", new ArrayListHandler());
System.out.println(list);
}
(3)BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
//BeanHandler:将结果集中的第一行数据封装为JavaBean返回
@Test
public void test3() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
Account account = runner.query("select * from account", new BeanHandler<Account>(Account.class));
System.out.println(account.getProduct());
}
(4)BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
//BeanListHandler:将结果集中的每一行数据封装为JavaBean组成List返回
@Test
public void test4() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
List<Account> list = runner.query("select * from account", new BeanListHandler<Account>(Account.class));
System.out.println(list);
}
(5)MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
//MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
@Test
public void test5() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
Map<String, Object> map = runner.query("select * from account", new MapHandler());
System.out.println(map);
}
(6)MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
//MapListHandler:将结果集中的每一行数据封装到一个Map里,key是列名,value就是对应的值,所有的map组成一个List返回。
@Test
public void test6() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
List<Map<String, Object>> list= runner.query("select * from account", new MapListHandler());
System.out.println(list);
}
(7)ColumnListHandler:将结果集中某一列的数据存放到List中。
//ColumnListHandler:将结果集中某一列的数据存放到List中。
@Test
public void test7() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
List<Object>list = runner.query("select * from account", new ColumnListHandler());
System.out.println(list);
}
(8)KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里(List<Map>),再把这些map再存到一个map里,其key为指定的列。
//KeyedHandler:将结果集中的每一行数据都封装到一个Map里(List<Map>),再把这些map再存到一个map里,其key为指定的列
@Test
public void test8() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
Map<Object, Map<String, Object>> map= runner.query("select * from account", new KeyedHandler("id"));
System.out.println(map);
}
(9)Long long = (Long)queryRunner.query("select count(*) from account",new ScalarHandler(1));//进行单值查询。。。。。。
public void test9() throws SQLException{
QueryRunner runner = new QueryRunner(new ComboPooledDataSource());
long count = (Long)runner.query("select count(*) from account", new ScalarHandler());
System.out.println(count);
}
相关文章推荐
- JDBC高级开发(3)--Apache—DBUtils框架
- 简单的三层框架以及使用dbutils进行数据库操作(入门)
- 简单的三层框架以及使用dbutils进行数据库操作(入门)
- JDBC【数据库连接池、DbUtils框架、分页】
- 数据库连接池c3p0优化开源框架Dbutils的简单介绍
- 简单的三层框架以及使用dbutils进行数据库操作(入门)
- 自定义JDBC框架(仿DBUtils)
- Java_常瑞鹏 JDBC框架 和 Apache—DBUtils框架
- Java Web(十) JDBC的增删改查,C3P0等连接池,dbutils框架的使用
- JDBC框架 和 Apache—DBUtils框架
- 简单的三层框架以及使用dbutils进行数据库操作(入门)
- 模仿dbutils的jdbc框架
- JDBC框架 和 Apache—DBUtils框架
- JDBC第四篇--【数据库连接池、DbUtils框架、分页】
- JDBC【数据库连接池、DbUtils框架、分页】
- 通过DBUtils和C3P0结合简单实现增删改功能简化使用JDBC
- 第十七天dbutils的使用------Commons DbUtils(Apache)第三方的:只是对JDBC编码进行了简单的封装
- JDBC【数据库连接池、DbUtils框架、分页】
- Java Web(十) JDBC的增删改查,C3P0等连接池,dbutils框架的使用
- JDBC连接数据库之DBUtils简单使用(6)