在使用之前需要有一些准备,我使用的是mysql数据库
这里创建的就是一个测试类,中间使用的注释@Test就类似于main函数,可以直接右击run as————》JUnit Test就可以运行,但是提前是你要有 import org.junit.Test这个包
package com.qf.test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.qf.entity.Student;
//测试类
public class MyTest1 {
// 单元测试---实现增删改
/*
* 单元测试方法要求: 1、public修饰 2、无返回值 3、无形式参数
*/
@Test
public void test1() throws SQLException {
// 创建操作对象
QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
// 新增
// 执行非查询语句,返回受影响的行数
// System.out.println("新增:"+qr.execute("insert into
// tb_student(name,age,sex) values(?,?,?)", "李四",21,"男"));
// 修改
// System.out.println("修改:"+qr.execute("update tb_student set name=?
// where id=?", "小四",2));
// 删除
System.out.println("删除:" + qr.execute("delete from tb_student where id=?", 1));
}
// 查询--原生接口
@Test
public void test2() throws SQLException {
// 执行查询
QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
// 原生的,直接使用内部的接口完成结果集的赋值
Student stu = qr.query("select * from tb_student where id=2", new ResultSetHandler<Student>() {
@Override
public Student handle(ResultSet rs) throws SQLException {
// TODO Auto-generated method stub
Student student = new Student();
if (rs.next()) {
student.setAge(rs.getInt("age"));
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex"));
}
return student;
}
});
System.out.println(stu.getName());
}
// 查询--默认实现,支持对象
@Test
public void test3() throws SQLException {
// 执行查询
QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
// 执行查询,单个对象,需要传递对应类的Class对象
Student stu = qr.query("select * from tb_student where id=2", new BeanHandler<>(Student.class));
System.out.println("查询单个:" + stu.getName());
}
// 添加--批处理,支持多个数据添加操作
@Test
public void test4() throws SQLException {
// 执行查询
QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
// sql语句
String sql = "insert into tb_student(name,age,sex) values(?,?,?)";
Object[][] vs = new Object[10][3];
for (int i = 0; i < vs.length; i++) {
vs[i][0] = "麻子" + i;
vs[i][1] = i * 10;
vs[i][2] = "女";
}
// 执行批处理,返回每条语句的受影响的行数
int[] cs = qr.batch(sql, vs);
System.out.println(Arrays.toString(cs));
}
//查询--返回多条数据---集合
@Test
public void test5() throws SQLException {
// 执行查询
QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
List<Student> list=qr.query("select * from tb_student",
new BeanListHandler<>(Student.class));
for(Student s:list){
System.out.println(s.getName());
}
}
}
这是最后数据库的显示结果