Java的DBUtils工具演示

Java的DBUtils工具演示

掌握 DbUtils工具的關鍵是:學好2個(類+接口)

1、QueryRunner類 用於執行SQL語句
2、ResultSetHandler接口 用於封裝返回結果 具體使用時 是用他的實現類

在演示中我使用的是c3p0連接池。

/* SQL腳本
     * CREATE TABLE person(
        id VARCHAR(32) PRIMARY KEY,
        NAME VARCHAR(32),
        address VARCHAR(30),
        age INT 
        );
        還要建立person的值對象
     */
@Test //不帶事務的增,不帶事務會自動幫我們關流   Statement
    public void save1() throws Exception {
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
        String sql="INSERT INTO person VALUES('A002','Jack','長沙',25);";
        run.update(sql);
    }
    @Test //不帶事務的增,PreparedStatement
    public void save2() throws Exception {
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
        //可變參數,內部會自動幫我們把參數賦值給對應序號的佔位符'?'
        run.update("INSERT INTO person VALUES('A003','Rose',?,?)","湖南益陽",20);
    }
    @Test //帶事務的增,PreparedStatement
    public void save3() throws Exception {
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
        //事務
        Connection  con=C3p0Pool.getConnection();
        try {
            con.setAutoCommit(false);
            //結果 錯誤的回滾了,正確的進庫了
            run.update("INSERT INTO person VALUES('A004','張三',?,?)","益陽",28);
            run.update("INSERT INTO person VALUES('A003','李四',?,?)","杭州",24);
            con.commit();
        } catch (Exception e) {
            con.rollback();
            System.out.println("事務回滾...");
        }finally{
            con.setAutoCommit(true);
            con.close();
        }
    }
    @Test //帶事務的增,PreparedStatement
    public void save4() throws Exception {
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
        //事務
        Connection  con=C3p0Pool.getConnection();
        try {
            con.setAutoCommit(false);
            //結果 使用同一個con,都回滾了
            run.update(con,"INSERT INTO person VALUES('A004','張三',?,?)","益陽",28);
            run.update(con,"INSERT INTO person VALUES('A003','李四',?,?)","杭州",24);
            con.commit();
        } catch (Exception e) {
            con.rollback();
            System.out.println("事務回滾...");
        }finally{
            con.setAutoCommit(true);
            con.close();
        }
    }
    @Test //使用DBuUtils 進行刪除和修改,原理同新增
    public void update() throws Exception {
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
        run.update("update person set age=age-2");

    }

在查詢中,重新過in寫了一個值對象,其中的arrdess改成addr。

//查詢
    @Test //封裝成MapList
    public void query() throws Exception {
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
        String sql = "select * from person ";
        List<Map<String, Object>> person = run.query(sql, new MapListHandler());
        System.out.println(person);
    }
    @Test //封裝成BeanList
    public void query2() throws Exception {
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
        String sql = "select * from person ";
        List<Person> person = run.query(sql, new BeanListHandler<Person>(Person.class));
        System.out.println(person);
    }
    @Test //如果出現值對象中屬性名和表字段名不相同,則需要別名
    public void query3() throws Exception {
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
        //用別名解決不一致的情況
        String sql = "select id,name,address,age from person ";
        List<Person2> person2 = run.query(sql, new BeanListHandler<Person2>(Person2.class));
        System.out.println(person2);
    }
    @Test //帶參數
    public void query4() throws Exception {
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
        //使用佔位符設置參數
        String sql = "select id,name,address,age from person where name like ? and age > ? ";
        List<Person2> person2 = run.query(sql, new BeanListHandler<Person2>(Person2.class),"%j%",18);
        System.out.println(person2);
    }

演示擴展包內容

/////以下演示---擴展包和批處理////
    //自動生成sql語句,我們必須在JavaBean中添加相應的註解,讓我們省去寫sql語句
    @Test  //直接讓給擴展包內部,幫我們利用Person值對象
    public void query5()  throws Exception{
        //該方式必須給Person類添加註解   @Table(value="person")//對應的數據庫表
        ExtQueryRunner run = new ExtQueryRunner(C3p0Pool.getDataSource());
        List<Person> person = run .query(Person.class);
        System.out.println(person);
    }
    @Test   //  O/R  Object/Relation  對象/關係
    public void save5() throws Exception{
        //該方式下  需要在  值對象的屬性中加@Column
        Person p = new Person();
        p.setId("A005");
        p.setAge(30);
        p.setName("MMMM");
        ExtQueryRunner run = new ExtQueryRunner(C3p0Pool.getDataSource());

        run.save(p);
    }
    @Test   // 不一致的 添加
    public void save6() throws Exception{
        //該方式下  需要在  值對象的屬性中加@Column
        Person2 p = new Person2();
        p.setId("A006");
        p.setAge(30);
        p.setName("ddddd");
        p.setAddr("XXX");
        ExtQueryRunner run = new ExtQueryRunner(C3p0Pool.getDataSource());
        run.save(p);
    }
    //批處理
    @Test   
    public void dom() throws Exception{
        QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());

        for(int i = 0 ; i <100;i++){
            String sql="insert into stud values(?,?)";
            String [][] values={
                    {"Q001"+i,"Jack"+i},
                    {"Q002"+i,"Tomm"+i}
            };
            run.batch(sql, values);
        }

    }

附錄

將獲取連接做成工具

public class C3p0Pool {
    private static DataSource ds;// 單例的池
    private static ThreadLocal<Connection> t = new ThreadLocal<Connection>();
    static {
        try {
            ds =new ComboPooledDataSource();
        } catch (Exception e) {
            throw new RuntimeException("數據庫連接池創建失敗!");
        }
    }

    // 以後會用到這個功能 :
    public static DataSource getDataSource() {
        return ds;
    }

    public static Connection getConnection() {
        Connection con = t.get();
        if (con == null) {
            try {
                con = ds.getConnection();
                t.set(con);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return con;
    }

    public static void cleanConFromThradeLocal() {
        t.set(null);
    }
}

連接池的工具包
http://pan.baidu.com/s/1hrQBXyO

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章