代码使用案例:(commons-dbutils-1.4)
@Test//原来不使用dbUtils工具的数据库查询代码实现
public void jdbcQuery() throws Exception{
List studs = new ArrayList();
Connection con = C3p0Pool.getConnection();
String sql = "select * from stud ";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
Stud s = new Stud();
s.setId(rs.getString("id"));
s.setName(rs.getString("name"));
studs.add(s);
}
System.out.println(studs);
}
@Test//使用dbUtils工具的数据库查询代码实现
public void dbUtilsQuery() throws Exception{
QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
String sql = "select * from stud ";
List studs = run.query(sql,new BeanListHandler(Stud.class) );
System.out.println(studs);
}
@Test
public void dbUtilsQuery2() throws Exception{
QueryRunner run = new QueryRunner(C3p0Pool.getDataSource());
String sql = "select * from stud ";
List
ext增强操作,去除sql语句操作数据库:
////////以下演示扩展包commons-dbutilss-ext.jar的功能//////////////
//注意,下面的用法要生效,必须给值对象添加注解
@Test//封装成BeanList---直接通过JavaBean的字节码查询
public void query4() throws Exception{
ExtQueryRunner run = new ExtQueryRunner(C3p0Pool.getDataSource());
List persons = run.query(Person.class);//不用sql语句,,直接查询Bean-List
System.out.println(persons);
}
@Test//封装成BeanList---直接通过JavaBean的字节码查询
public void save3() throws Exception{
ExtQueryRunner run = new ExtQueryRunner(C3p0Pool.getDataSource());
Stud stud = new Stud();
stud.setId("A006");
stud.setName("Alice");
run.save(stud);//不用sql语句,,直接存对象
System.out.println(stud);
}
注意:使用ext,值对象要加注解
@Table(value="person")
public class Person {
private String id;
private String name;
@Column(value="address")//该注解无效,反正以后开发时属性名都取成和表字段名一样
private String addr;
private Integer age;
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 String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
updata delete 函数要加入id注解:
@Id
private double salay;
@Column
private int age;
@Column
private String name;
@Column
private String id;
@Column
private String sex;
sql语句为:update column注解 from table注解 where id注解