QueryRunner的使用

在相繼學習了JDBC和數據庫操做以後,咱們明顯感到編寫JDBC代碼並不是一件輕鬆的事兒。爲了幫助咱們更高效的學習工做,從JDBC的繁重代碼中解脫出來,老佟給咱們詳盡介紹了一個簡化JDBC操做的組件——DBUtils。咱們今天主要學習了它所提供的兩個類和一個接口。

組件下載地址:http://commons.apache.org/dbutils/java

DbUtils類(org.apache.commons.dbutils.DbUtils)主要負責裝載驅動、關閉鏈接的常規工做。sql

1.       close: 檢查所提供的參數是否是NULL,若是不是的話,它們就關閉鏈接、聲明和結果集。數據庫

2.       CloseQuietly:避免鏈接、聲明或結果集爲NULL的狀況被關閉。apache

3.       CommitAndCloseQuietly(Connection conn):用來提交鏈接,而後關閉鏈接,而且在關閉鏈接時不向上拋出在關閉時發生的一些SQL異常。數組

4.       LoadDriver(String driveClassName): 裝載並註冊JDBC驅動程序,若是成功就返回TRUE。oracle

QreryRunner類(org.apache.commons.dbutils.QueryRunner) 顯著的簡化了SQL查詢,並與ResultSetHandler協同工做將使編碼量大爲減小。post

1.       query(Connection conn, String sql, Object[] params, ResultSetHandler rsh):執行選擇查詢,在查詢中,對象陣列的值被用來做爲查詢的置換參數。學習

2.       query(String sql, Object[] params, ResultSetHandler rsh):方法自己不提供數據庫鏈接,執行選擇查詢,在查詢中,對象陣列的值被用來做爲查詢的置換參數。ui

3.       query(Connection conn, String sql, ResultSetHandler rsh):執行無需參數的選擇查詢。編碼

4.       update(Connection conn, String sql, Object[] params):被用來執行插入、更新或刪除(DML)操做。

ResultSetHandler接口(org.apache.commons.dbutils.ResultSethandler)執行處理一個結果集對象,將數據轉變並處理爲任何一種形式,供其餘應用使用。

1.       Object handle (java.sql.ResultSet .rs) :結果集(ResultSet)做爲參數傳入方法內,處理這個結果集,返回一個對象。

ArrayHandler

ArrayListHandler

BeanHandler

BeanListHandler

MapHandler

MapListHandler

ScalarHandler

咱們學習了此組件的兩個類和一個接口之後,寫了下列代碼供參考。

import java.sql.Connection;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;

import org.apache.commons.dbutils.handlers.BeanListHandler;

public class TestQueryRunner {

         public static void main(String[] args) throws SQLException {

                   // TODO Auto-generated method stub

                   //queryOracle();

                   update();

         }

        

         private static void update() throws SQLException{

                   QueryRunner runner = new QueryRunner();

                   Connection conn = DBManager.getConnection();

                   //刪除非 manager 中工資 低於 5000 的員工

                   String sql = "UPDATE examstudent SET student_name = ? WHERE flow_id = ?";

                   Object [] params = new Object[]{"Jerry", 5000};

                  

                   runner.update(conn, sql, params);

         }

        

         private static void insert() throws SQLException{

                   QueryRunner runner = new QueryRunner();

                   Connection conn = DBManager.getConnection();

                   //刪除非 manager 中工資 低於 5000 的員工

                 String sql = "INSERT INTO examstudent(flow_id, type, id_card, exam_card, student_name, location, grade) VALUES(?, ?, ?, ?, ?, ?, ?)";

                   Object [] params = new Object[]{5000, 6, "身份證", "准考證", "Tom", "北京", 99};

                  

                   runner.update(conn, sql, params);

         }

        

         private static void delete() throws SQLException{

                   QueryRunner runner = new QueryRunner();

                   Connection conn = DBManager.getConnection();

                   //刪除非 manager 中工資 低於 5000 的員工

                   String sql = "delete from employees " +

                                                "where employee_id not in " +

                                                "     (select distinct d.manager_id from departments d where d.manager_id is not null) " +

                                                "and salary < ?";

                   System.out.println(sql);

                   Object [] params = new Object[]{5000};

                  

                   runner.update(conn, sql, params);

         }

        

         private static void queryOracle() throws SQLException{

                   QueryRunner runner = new QueryRunner();

                   Connection conn = DBManager.getConnection();

                   //oracle 中的別名能夠別解析

                   String sql = "SELECT flow_id flowid, type, id_card idcard, exam_card examcard, student_name studentname, location, grade FROM examstudent";

                   Object obj = runner.query(conn, sql, new BeanListHandler(ExamStudent.class));

                   System.out.println(obj);

         }

         private static void query() throws SQLException {

                   //1. 建立一個 QueryRunner 的實例

                   QueryRunner runner = new QueryRunner();

                  

                  

                   Connection conn = DBManager.getConnection();

                   String sql = "SELECT id, name, address, phone FROM customers WHERE name LIKE ?";

                   Class type = Customer.class;

                   Object [] params = new Object[]{"%%"};

                  

                   //2. 查詢操做

                   //conn: 查詢須要的數據庫鏈接, sql: 查詢使用的 sql 語句, rsh: 如何轉換查詢獲得的結果集, params: 填補 sql 語句參數的數組

                   Object obj = runner.query(conn, sql, new BeanListHandler(type), params);

                   //System.out.println("^^" + obj);

                  

                   sql = "SELECT flow_id flowid, type, id_card idcard, exam_card examcard, student_name studentname, location, grade FROM examstudent";

                   type = ExamStudent.class;

                  

                   obj = runner.query(conn, sql, new BeanListHandler(ExamStudent.class));

                   System.out.println(obj);

                   }

}

 

public class JdbcUtil {

private static ComboPooledDataSource dataSource =new ComboPooledDataSource();
public static ComboPooledDataSource getDataSource()
{
return dataSource;
}

}

src目錄下c3p0-config.xml

 

從數據庫中取count(*)數據

1         int topicNum=0;
2         QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());
3         String sql ="select count(*) from topic where type_id= ? order by time desc";
4         Object[] params={typeId};
5         topicNum=(int)(long) runner.query(sql,new ScalarHandler(),params);
6         return topicNum;

 

取一條數據   其中表的字段名字和類的名字要對應相同

1         Topic newlyTopic=null;
2         QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());
3         String sql ="select * from topic where type_id= ? order by time desc";
4         Object[] params={typeId};
5         newlyTopic= runner.query(sql,new BeanHandler<Topic>(Topic.class),params);
6         return newlyTopic;

 

取集合數據List<>返回    其中表的字段名字和類的名字要對應相同

1         List<Topic> topicList=new ArrayList<Topic>();
2         QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());
3         String sql ="select * from topic where type_id= ? order by time desc";
4         Object[] params={typeId};
5         topicList=runner.query(sql, new BeanListHandler<Topic>(Topic.class),params);
6         return topicList;

 插入

複製代碼
 1         QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());
 2         String sql ="insert into topic(name,author,content,time,type_id) values(?,?,?,?,?)";
 3         Object[] params={topic.getName(),topic.getAuthor(),topic.getContent(),topic.getTime(),topic.getTypeId()};
 4         try {
 5             //事務開始
 6             runner.update(sql,params);
 7             //事務提交
 8         } catch (SQLException e) {
 9             e.printStackTrace();
10             //事務回滾
11             throw e;
12         }
複製代碼

更新

複製代碼
 1         QueryRunner runner= new QueryRunner(JdbcUtil.getDataSource());
 2         String sql ="update topic set name=? , content=? , time=? where id= ?";
 3         Object[] params={topic.getName(),topic.getContent(),topic.getTime(),topic.getId()};
 4         try {
 5             //事務開始
 6             runner.update(sql,params);
 7             //事務提交
 8         } catch (SQLException e) {
 9             e.printStackTrace();
10             //事務回滾
11             throw e;
12         }
複製代碼
相關文章
相關標籤/搜索