`
张玉龙
  • 浏览: 737354 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
社区版块
存档分类
最新评论

[Apache commons系列]DBUtils简介-inkfish原创

阅读更多
[Apache commons系列]DBUtils简介

 来源(http://blog.csdn.net/inkfish )。

  DbUtils是一个小型的类库,这里通过具体实例来说明如何使用DbUtils。示例分为3个类:DbUtilsExample演示了如何使用DbUtils 类;QueryRunnerExample 演示了如何使用QueryRunner 、ResultSetHandler ;User 类为一个JavaBean,对应于数据库中的表格。示例采用MySQL为数据库,使用JDBC4.0驱动(最大的区别就是不需要写Class.forName().newInstance() )。(来源:http://blog.csdn.net/inkfish)

依赖包: (来源:http://blog.csdn.net/inkfish)

    * commons-dbcp-1.2.2.jar:提供数据库连接池
    * commons-dbutils-1.3.jar:DbUtils包
    * commons-lang-2.4.jar:提供常用的工具方法
    * commons-pool-1.5.3.jar:提供DBCP对象池化机制
    * mysql-connector-java-5.1.10-bin.jar:MySQL JDBC4.0驱动

建表语句: (来源:http://blog.csdn.net/inkfish)

view plaincopy to clipboardprint?

   DROP TABLE IF EXISTS `user`;  
   CREATE TABLE  `user` (  
     `USERNAME` varchar(30) NOT NULL,  
     `PASSWORDHASH` varchar(256),  
     PRIMARY KEY (`USERNAME`),  
     KEY `USERNAME` (`USERNAME`)  
   );  

DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `USERNAME` varchar(30) NOT NULL, `PASSWORDHASH` varchar(256), PRIMARY KEY (`USERNAME`), KEY `USERNAME` (`USERNAME`) );

DbUtilsExample.java :

view plaincopy to clipboardprint?

   import java.sql.Connection;  
   import java.sql.DriverManager;  
   import java.sql.PreparedStatement;  
   import java.sql.ResultSet;  
   import java.sql.SQLException;  
   import java.sql.Statement;  
   import org.apache.commons.dbutils.DbUtils;  
   public class DbUtilsExample {  
       public static void main(String[] args) {  
           String url = "jdbc:mysql://127.0.0.1:3306/test";  
           String user = "test";  
           String password = "test";  
           Connection conn = null;  
           Statement stmt = null;  
           ResultSet rs = null;  
           try {  
               conn = DriverManager.getConnection(url, user, password);  
               stmt = conn.createStatement();  
               stmt  
                       .executeUpdate("INSERT INTO user (USERNAME, PASSWORDHASH) values ('testUser', '123456')");  
               DbUtils.closeQuietly(stmt);  
               DbUtils.commitAndCloseQuietly(conn);  
           } catch (SQLException ex) {  
               DbUtils.printStackTrace(ex);  
               DbUtils.rollbackAndCloseQuietly(conn);  
           }  
           PreparedStatement psmt = null;  
           try {  
               conn = DriverManager.getConnection(url, user, password);  
               psmt = conn.prepareStatement("SELECT USERNAME, PASSWORDHASH FROM user");  
               rs = psmt.executeQuery();  
               while (rs.next()) {  
                   System.out.println(rs.getString(1) + "\t" + rs.getString(2));  
               }  
           } catch (SQLException ex) {  
               DbUtils.printStackTrace(ex);  
           } finally {  
               DbUtils.closeQuietly(conn, psmt, rs);  
           }  
           try {  
               conn = DriverManager.getConnection(url, user, password);  
               stmt = conn.createStatement();  
               stmt.executeUpdate("DELETE FROM user WHERE USERNAME='testUser'");  
               DbUtils.closeQuietly(stmt);  
           } catch (SQLException ex) {  
               DbUtils.printStackTrace(ex);  
           } finally {  
               DbUtils.printWarnings(conn);  
               DbUtils.closeQuietly(conn);  
           }  
       }  
   }  
   import java.sql.Connection;                                                                                     
   import java.sql.DriverManager;                                                                                  
   import java.sql.PreparedStatement;                                                                              
   import java.sql.ResultSet;                                                                                      
   import java.sql.SQLException;                                                                                   
   import java.sql.Statement;                                                                                      
   import org.apache.commons.dbutils.DbUtils;                                                                      
   public class DbUtilsExample {                                                                                   
       public static void main(Stringa[] args) {                                                                   
           String url = "jdbc:mysql://127.0.0.1:3306/test";                                                        
           String user = "test";                                                                                   
           String password = "test";                                                                               
           Connection conn = null;                                                                                 
           Statement stmt = null;                                                                                  
           ResultSet rs = null;                                                                                    
           try {                                                                                                   
               conn = DriverManager.getConnection(url, user, password);                                            
               stmt = conn.createStatement();                                                                      
               stmt                                                                                                
                       .executeUpdate("INSERT INTO user (USERNAME, PASSWORDHASH) values ('testUser', '123456')");  
               DbUtils.closeQuietly(stmt);                                                                         
               DbUtils.commitAndCloseQuietly(conn);                                                                
           } catch (SQLException ex) {                                                                             
               DbUtils.printStackTrace(ex);                                                                        
               DbUtils.rollbackAndCloseQuietly(conn);                                                              
           }                                                                                                       
           PreparedStatement psmt = null;                                                                          
           try {                                                                                                   
               conn = DriverManager.getConnection(url, user, password);                                            
               psmt = conn.prepareStatement("SELECT USERNAME, PASSWORDHASH FROM user");                            
               rs = psmt.executeQuery();                                                                           
               while (rs.next()) {                                                                                 
                   System.out.println(rs.getString(1) + "\t" + rs.getString(2));                                   
               }                                                                                                   
          } catch (SQLException ex) {                                                                              
              DbUtils.printStackTrace(ex);                                                                         
          } finally {                                                                                              
              DbUtils.closeQuietly(conn, psmt, rs);                                                                
          }                                                                                                        
          try {                                                                                                    
              conn = DriverManager.getConnection(url, user, password);                                             
              stmt = conn.createStatement();                                                                       
              stmt.executeUpdate("DELETE FROM user WHERE USERNAME='testUser'");                                    
              DbUtils.closeQuietly(stmt);                                                                          
          } catch (SQLException ex) {                                                                              
              DbUtils.printStackTrace(ex);                                                                         
          } finally {                                                                                              
              DbUtils.printWarnings(conn);                                                                         
              DbUtils.closeQuietly(conn);                                                                          
          }                                                                                                        
      }                                                                                                            
  }                                                                                                                

QueryRunnerExample.java : (来源:http://blog.csdn.net/inkfish)

view plaincopy to clipboardprint?

import static java.lang.System.out;  
import java.sql.Connection;  
import java.sql.PreparedStatement;  
import java.sql.SQLException;  
import java.util.Arrays;  
import java.util.List;  
import java.util.Map;  
import javax.sql.DataSource;  
import org.apache.commons.dbcp.BasicDataSource;  
import org.apache.commons.dbutils.DbUtils;  
import org.apache.commons.dbutils.QueryRunner;  
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 org.apache.commons.dbutils.handlers.ColumnListHandler;  
import org.apache.commons.dbutils.handlers.KeyedHandler;  
import org.apache.commons.dbutils.handlers.MapHandler;  
import org.apache.commons.dbutils.handlers.MapListHandler;  
import org.apache.commons.dbutils.handlers.ScalarHandler;  
import org.apache.commons.lang.StringUtils;  
public class QueryRunnerExample {  
    public static void main(String[] args) throws SQLException {  
        QueryRunnerExample example = new QueryRunnerExample();  
        example.batch();  
        example.fillStatement();  
        example.query();  
        example.update();  
        example.closeDataSource();  
    }  
    private DataSource dataSource = null;  
    private QueryRunner runner = null;  
    public QueryRunnerExample() {  
        initDataSource();  
        runner = new QueryRunner(dataSource);  
    }  
    private void batch() {  
        String sql = "INSERT INTO user (USERNAME, PASSWORDHASH) values (?, ?)";  
        try {  
            out.println("\n" + StringUtils.center("Test QueryRunner batch", 80, '*'));  
            int[] result = runner.batch(sql, new Object[][] { { "user1", "pwd1" },  
                    { "user2", "pwd2" }, { "user3", "pwd3" }, { "user4", "pwd4" } });  
            out.printf("运行结果:%s\n", Arrays.toString(result));  
        } catch (SQLException ex) {  
            DbUtils.printStackTrace(ex);  
        }  
    }  
    private void closeDataSource() throws SQLException {  
        ((BasicDataSource) dataSource).close();  
    }  
    private void fillStatement() throws SQLException {  
        String sql = "INSERT INTO user (USERNAME, PASSWORDHASH) VALUES (?, ?)";  
        Connection conn = null;  
        try {  
            out.println("\n" + StringUtils.center("Test QueryRunner fillStatement", 80, '*'));  
            conn = dataSource.getConnection();  
            PreparedStatement psmt = conn.prepareStatement(sql);  
            runner.fillStatementWithBean(psmt, new User("testUser5", "pwd5"), "userName",  
                    "passwordHash");  
            out.println(psmt.executeUpdate());  
        } catch (SQLException ex) {  
            DbUtils.printStackTrace(ex);  
        } finally {  
            DbUtils.commitAndCloseQuietly(conn);  
        }  
    }  
    private DataSource initDataSource() {  
        if (dataSource == null) {  
            BasicDataSource basicDs = new BasicDataSource();  
            basicDs.setUrl("jdbc:mysql://127.0.0.1:3306/test");  
            basicDs.setUsername("test");  
            basicDs.setPassword("test");  
            this.dataSource = basicDs;  
        }  
        return dataSource;  
    }  
    private void query() throws SQLException {  
        out.println("\n" + StringUtils.center("Test QueryRunner query", 80, '*'));  
        String sql = "SELECT * FROM user WHERE USERNAME LIKE ?";  
        out.println("1.Test QueryRunner query, ArrayHandler");  
        //把ResultSet第一行包装成Object[]  
        Object[] r1 = runner.query(sql, new ArrayHandler(), "user%");  
        out.println("  " + Arrays.deepToString(r1));  
        out.println("2.Test QueryRunner query, ArrayListHandler");  
        //把ResultSet包装成List<Object[]>  
        List<Object[]> r2 = runner.query(sql, new ArrayListHandler(), "user%");  
        out.println("  " + Arrays.deepToString(r2.toArray()));  
        out.println("3.Test QueryRunner query, BeanHandler");  
        //把ResultSet第一行包装成一个JavaBean  
        User r3 = runner.query(sql, new BeanHandler<User>(User.class), "user%");  
        out.println("  " + r3.toString());  
        out.println("4.Test QueryRunner query, BeanListHandler");  
        //把ResultSet第一行包装成一个List<JavaBean>;  
        List<User> r4 = runner.query(sql, new BeanListHandler<User>(User.class), "user%");  
        out.println("  " + Arrays.deepToString(r4.toArray()));  
        out.println("5.Test query, ColumnListHandler");  
        //抽取ResultSet指定的列,以List<Object>对象的形式返回,默认第一列  
        List<Object> r5 = runner.query(sql, new ColumnListHandler(2), "user%");  
        out.println("  " + Arrays.deepToString(r5.toArray()));  
        out.println("6.Test QueryRunner query, KeyedHandler");  
        //包装ResultSet,以Map<Object,Map<String,Object>>对象形式返回,第一个Object是指定的列值,第二个Map中String是列名且对大小写不敏感  
        Map<Object, Map<String, Object>> r6 = runner.query(sql, new KeyedHandler(2), "user%");  
        out.println("  " + r6.toString());  
        out.println("7.Test QueryRunner query, MapHandler");  
        //把ResultSet第一行包装成Map<String, Object>,key对大小写不敏感  
        Map<String, Object> r7 = runner.query(sql, new MapHandler(), "user%");  
        out.println("  " + r7.toString());  
        out.println("8.Test QueryRunner query, MapListHandler");  
        //把ResultSet包装成List<Map<String,Object>>>,Map的key对大小写不敏感  
        List<Map<String, Object>> r8 = runner.query(sql, new MapListHandler(), "user%");  
        out.println("  " + r8.toString());  
        out.println("9.Test QueryRunner query, ScalarHandler");  
        //抽取ResultSet第一行指定列,以Object对象形式返回  
        Object r9 = runner.query(sql, new ScalarHandler("passwordhash"), "user%");  
        out.println("  " + r9.toString());  
    }  
    private void update() {  
        String sql = "DELETE FROM user WHERE PASSWORDHASH LIKE ?";  
        try {  
            out.println("\n" + StringUtils.center("Test QueryRunner update", 80, '*'));  
            out.println(runner.update(sql, "pwd%"));  
        } catch (SQLException ex) {  
            DbUtils.printStackTrace(ex);  
        }  
    }  
}  


分享到:
评论

相关推荐

    commons-dbutils-1.7-API文档-中文版.zip

    赠送jar包:commons-dbutils-1.7.jar; 赠送原API文档:commons-dbutils-1.7-javadoc.jar; 赠送源代码:commons-dbutils-1.7-sources.jar; 赠送Maven依赖信息文件:commons-dbutils-1.7.pom; 包含翻译后的API文档...

    commons-dbutils-1.7.rar

    commons-dbutils-1.7.jar,commons-dbutils-1.7-javadoc.jar,commons-dbutils-1.7-sources.jar,commons-dbutils-1.7-tests.jar,commons-dbutils-1.7-test-sources.jar

    commons-dbutils-1.4.jar

    在实际项目中,"commons-dbutils-1.4.jar"可以与Apache的另一个项目——Apache Commons DBCP(数据库连接池)配合使用,以实现数据库连接的池化管理,进一步提升系统性能。例如,可以通过BasicDataSource来配置和...

    commons-dbutils-1.7.jar

    commons-dbutils-1.7.jar 最新

    commons-dbutils-1.6.rar所有jar包

    这个压缩包文件"commons-dbutils-1.6.rar"包含了DBUtils的1.6版本,这是一个非常受欢迎的开源项目,用于简化Java数据库编程。DBUtils的核心理念是通过提供实用程序类来消除JDBC的繁琐和易错性,使开发人员能够更专注...

    commons-dbutils-1.3.zip

    这个压缩包“commons-dbutils-1.3.zip”包含的是DBUtils库的1.3版本。DBUtils库是Apache Commons项目的一部分,旨在提供一个简单、安全的方式来处理数据库操作,减少与数据库交互时出现的常见错误。 DBUtils的核心...

    commons-dbutils-1.6

    这个项目在1.6版本中包含了两个主要的jar文件:`commons-dbutils-1.6.jar`和`commons-dbutils-1.6-sources.jar`。 `commons-dbutils-1.6.jar`是运行时库,它提供了大量的静态方法来处理数据库操作。这个库的核心...

    commons-dbutils-1.6.jar

    commons-dbutils-1.6.jar

    commons-dbutils-1.7-API文档-中英对照版.zip

    赠送jar包:commons-dbutils-1.7.jar; 赠送原API文档:commons-dbutils-1.7-javadoc.jar; 赠送源代码:commons-dbutils-1.7-sources.jar; 赠送Maven依赖信息文件:commons-dbutils-1.7.pom; 包含翻译后的API文档...

    commons-dbutils-1.7

    Apache Commons DbUtils是Java开发中的一个实用工具库,专门针对JDBC(Java Database Connectivity)进行优化,以提供更简洁、高效的数据库操作API。这个库在Java社区中广泛使用,因为它大大减轻了开发者处理数据库...

    commons-dbutils-1.6的jar包

    好用的commons-dbutils-1.6的jar工具包,其中是包含3个:commons-dbutils-1.6.jar、commons-dbutils-1.6-javadoc.jar和commons-dbutils-1.6-sources.jar

    Commons-dbutils1.7 jar包.rar

    commons-dbutils包是Apache开源组织提供的用于操作数据库的工具包。简单来讲,这个工具包就是用来更加方便我们操作数据库的,最近工作中使用了一下,感觉确实方便很多,基本告别自己封装JDBC代码对数据库进行增删改...

    commons-dbutils.jar.rar

    `commons-dbutils.jar.rar` 是一个包含Apache Commons DBUtils库的不同版本的压缩文件,主要用于Java应用程序中的数据库操作。DBUtils是一个实用程序库,它简化了JDBC(Java Database Connectivity)的使用,提供了...

    commons-dbutils-1.5.jar

    commons-dbutils-1.5.jar

    commons-dbutils-1.6.jar包

    包org.apache.commons.dbutils DbUtils是一个为简化JDBC操作的小类库. 接口摘要 ResultSetHandler 将ResultSet转换为别的对象的工具. RowProcessor 将ResultSet行转换为别的对象的工具. 类摘要 BasicRowProcessor ...

    commons-dbutils-1.1,commons-dbutils-1.3资源包

    Apache Commons DBUtils是一个Java库,它为处理数据库连接提供了简单且实用的工具。这个资源包包含了两个版本,即1.1和1.3,它们都是Apache软件基金会开发并维护的开源项目。DBUtils的主要目标是简化数据库编程,...

Global site tag (gtag.js) - Google Analytics