資料庫連線池工具---DbUtils
阿新 • • 發佈:2018-11-29
DbUtils
DbUtils是基於c3p0來做的,功能很是強大。
首先做一個c3p0的連線池C3p0Pool:
相關的知識點都寫在裡程式碼的註解中了,下面是程式碼:package cn.hncu.c3p0; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; //我們的這個包裝,只是為了把c3p0池做成讓每個執行緒(客戶端)獲得的是同一個連線,方便做b/s框架下的事務 public class C3p0Pool { private static DataSource pool; private static ThreadLocal<Connection> t=new ThreadLocal<Connection>(); static { pool=new ComboPooledDataSource(); } public static DataSource getDataSource(){ return pool; } public static Connection getConnection() throws SQLException{ Connection con=t.get(); if (con==null){ con=pool.getConnection(); t.set(con); } return con; } }
上面程式碼中使用到的兩個封裝物件用的類如下:package cn.hncu.dbutils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ext.ExtQueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.MapListHandler; import org.junit.Test; import cn.hncu.c3p0.C3p0Pool; public class DbutilsDemo { @Test//原來不使用dbUtils工具的資料庫查詢程式碼實現 public void jdbcQuery() throws Exception{ List<Stud> list=new ArrayList<Stud>(); Connection con=C3p0Pool.getConnection(); String sql="select * from stud"; Statement st=con.createStatement(); ResultSet rs=st.executeQuery(sql); while (rs.next()){ Stud stud=new Stud(); stud.setId(rs.getString("id")); stud.setName(rs.getString("name")); stud.setAge(rs.getInt("age")); list.add(stud); } System.out.println(list); } @Test//使用dbUtils工具的資料庫查詢程式碼實現 public void dbutilsQuery() throws Exception{ QueryRunner run=new QueryRunner(C3p0Pool.getDataSource()); String sql="select * from stud"; List<Stud> stud=run.query(sql, new BeanListHandler<Stud>(Stud.class)); System.out.println(stud); } @Test public void dbutilsQuery2() throws Exception{ QueryRunner run=new QueryRunner(C3p0Pool.getDataSource()); String sql="select * from stud"; List<Map<String, Object>> stud=run.query(sql, new MapListHandler()); System.out.println(stud); } ////DbUtils工具的使用演示: 增刪改--用update(), 查--用query()方法 /* CREATE TABLE person( id VARCHAR(30) PRIMARY KEY, NAME VARCHAR(30), address VARCHAR(30), age INT ); */ @Test public void save() throws Exception{ QueryRunner run=new QueryRunner(C3p0Pool.getDataSource()); //Statement方式 //run.update("insert into dbutilsperson(id,name,address,age) values('A001','Jack','湖南長沙',22)"); //PrepareStatement方式 run.update("insert into dbutilsperson(id,name,address,age) values(?,?,?,?)", "A002","Tom","中國西安",24);//如果引數個數或型別 與 “?”號不匹配,會出異常 } @Test public void saveTx() throws Exception{ QueryRunner run=new QueryRunner(C3p0Pool.getDataSource()); Connection con=C3p0Pool.getConnection(); try { con.setAutoCommit(false); //※注意,實現事務功能時,要傳入con物件,且多條語句共處一個事務時,要傳入同一個con物件。但如果不實現事務功能,可以不傳入con物件 run.update(con, "insert into dbutilsperson(id,name,address,age) values(?,?,?,?)","A003","Tom","浙江杭州",24); run.update(con, "insert into dbutilsperson(id,name,address,age) values(?,?,?,?)","A003","Tom","浙江杭州",24); } catch (Exception e) { con.rollback(); System.out.println("事務回滾了"); } finally { con.setAutoCommit(true); con.close(); } } //下面演示一下查詢的結果集封裝功能 @Test//封裝成BeanList public void query1() throws Exception{ QueryRunner run=new QueryRunner(C3p0Pool.getDataSource()); //封裝成BeanList: 如果值物件中的屬性名和表中的欄位名不一致,那麼該屬性的值返回的是null----解決:採用別名,但是最好不要這樣做,在取名字的時候我們就應該要兩邊保持一致,不要這樣子自己坑自己 //List<Person> persons=run.query("select * from dbutilsperson", new BeanListHandler<Person>(Person.class));//沒有采用別名,addr屬性為null List<Person> persons=run.query("select id,name,address addr,age from dbutilsperson", new BeanListHandler<Person>(Person.class));//用屬性名 當 欄位別名 //如果你一定要像下面這句一樣不加別名的話就把Person類中的getAddr和setAddr改為getAddress和setAddress,因為QueryRunner的Query方法 //的類反射是根據資料庫欄位名來呼叫getter和setter方法的 //List<Person> persons=run.query("select id,name,address,age from dbutilsperson", new BeanListHandler<Person>(Person.class)); System.out.println(persons); } @Test//封裝成MapList public void query2() throws SQLException{ QueryRunner run=new QueryRunner(C3p0Pool.getDataSource()); String sql="select * from dbutilsperson"; List<Map<String, Object>> persons=run.query(sql, new MapListHandler()); System.out.println(persons); } @Test//封裝成BeanList---查詢帶引數 public void query3() throws SQLException{ QueryRunner run=new QueryRunner(C3p0Pool.getDataSource()); String sql="select id,name,address addr,age from dbutilsperson where name like ? and age>?"; List<Person> persons=run.query(sql, new BeanListHandler<Person>(Person.class), "%a%", 20);//用屬性名 當 欄位別名 System.out.println(persons); } @Test//演示批處理功能 public void batch() throws SQLException{ QueryRunner run=new QueryRunner(C3p0Pool.getDataSource()); for (int i=1;i<=100;i++){ String sql="insert into dbutilsstud(id,name) values(?,?)"; String str="000"+i; str=str.substring(str.length()-3, str.length()); String id1="A"+str; String id2="B"+str; String params[][]={{id1,"Jack"+i},{id2,"Rose"+i}}; run.batch(sql, params); } } ////////以下演示擴充套件包commons-dbutilss-ext.jar的功能////////////// //注意,下面的用法要生效,必須給值物件添加註解 @Test//封裝成BeanList---直接通過JavaBean的位元組碼查詢 public void query4(){ ExtQueryRunner run=new ExtQueryRunner(C3p0Pool.getDataSource()); List<Person> persons=run.query(Person.class); System.out.println(persons); } @Test//封裝成BeanList---直接通過JavaBean的位元組碼查詢 public void save3(){ ExtQueryRunner run=new ExtQueryRunner(C3p0Pool.getDataSource()); Stud stud=new Stud(); stud.setId("A06"); stud.setName("Jenney"); run.save(stud); System.out.println(stud); } }
下面兩個類加的註解都是為上面程式碼最後那一部分演示擴充套件包部分服務的
Person.java
package cn.hncu.dbutils; import org.apache.commons.dbutils.ext.Table; @Table(value = "dbutilsperson") public class Person { private String id; private String name; //@Column(value="address")//該註解無效,反正以後開發時屬性名都取成和資料庫表字段名一樣 //如果你一定要把這裡設的和資料庫裡面的欄位名不一樣,那麼請把這裡的getter和setter方法後的名字設定成和資料庫欄位名一樣的, //這樣照樣能設定,因為這個擴充套件包裡面的類反射獲取getter和setter方法是根據資料庫裡面的欄位名來設定的,我這裡就設定成了和資料 //庫欄位名一樣的,你們可以試試改成和本類的屬性名一樣的試試,一定無法取到值的 private String addr; private int age; public Person() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return addr; } public void setAddress(String addr) { this.addr = addr; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return id + ", " + name + ", " + addr + ", " + age; } }
Stud.java
package cn.hncu.dbutils;
import org.apache.commons.dbutils.ext.Column;
import org.apache.commons.dbutils.ext.Table;
@Table(value="dbutilsstud")
public class Stud {
@Column
private String id;
@Column
private String name;
private int age;
public Stud() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Stud other = (Stud) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return id + ", " + name + ", "+age;
}
}