一代码:
1.pom.xml
<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
2.DBUtils
public class TestDBUtils {
@Test
public void testdb(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
/*
DBUtils 只是帮我们简化了CRUD的代码,
连接的创建 和获取,不在他们的考虑范围内。
*/
QueryRunner queryRunner =new QueryRunner(dataSource);
try {
queryRunner.update("insert into day1 value (null,?)","dbutils");
} catch (SQLException e) {
e.printStackTrace();
}
/*
//针对增加 删除 修改
queryRunner.update(sql);
//针对 查询
queryRunner.update(sql,rsh);*/
}
}
二 new 实现匿名接口类
1.建立与表结构相同的dao:
package SpringWork.DBUtils;
public class Day1Dao {
private int id;
private String name;
@Override
public String toString() {
return "Day1Dao{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.Test
public class TestDBUtils {
@Test
public void testdb(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
/*
DBUtils 只是帮我们简化了CRUD的代码,
连接的创建 和获取,不在他们的考虑范围内。
*/
QueryRunner queryRunner =new QueryRunner(dataSource);
try {
//增加
// queryRunner.update("insert into day1 value (null,?)","dbutils");
Day1Dao dd = queryRunner.query("select * from day1 where id<?", new ResultSetHandler<Day1Dao>() {
@Override
public Day1Dao handle(ResultSet resultSet) throws SQLException {
Day1Dao ddao = new Day1Dao();
while (resultSet.next()){
int id =resultSet.getInt(1);
String name = resultSet.getString(2);
ddao.setName(name);
ddao.setId(id);
}
return ddao;
}
},14);
System.out.println(dd.toString());
} catch (SQLException e) {
e.printStackTrace();
}
/*
//针对增加 删除 修改
queryRunner.update(sql);
//针对 查询
queryRunner.update(sql,rsh);*/
}
}
二简化 BeanHandler
@Test
public void testdb(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
QueryRunner queryRunner =new QueryRunner(dataSource);
try {
Day1Dao dd = queryRunner.query(“select * from day1 where id =?”,new BeanHandler<
Day1Dao>(Day1Dao.class),14);
System.out.println(dd.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
三 查询多条 BeanListHandler
@Test
public void selectAll(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
QueryRunner queryRunner =new QueryRunner(dataSource);
try {
List<Day1Dao> list= queryRunner.query("select * from day1",new BeanListHandler<
Day1Dao>(Day1Dao.class));
for (Day1Dao dd:list
) {
System.out.println(dd);
}
} catch (SQLException e) {
e.printStackTrace();
}
}