DbUtils框架
DbUtils操作简单,功能强大;大部分功能都由三大核心实现:DbUtils工具类,ResultSetHandler接口,QueryRunner类
DbUtils工具类:关闭连接,加载驱动
ResultSetHandler接口:处理结果集
常用的实现类
QueryRunner类:增删改查
- 导jar包 DbUtiles的jar包
- 简单封装DBUtils
public class DBUtils {
//创建连接池
//我这里连接的是C3P0连接池,所以需要导C3P0的jar包
//如果用DBCP,导DBCP的包
//需要写数据库的配置文件,C3P0的配置文件同意命名为c3p0-config.xml,这个是命名规范,规定死了的
private static DataSource dataSource = new ComboPooledDataSource();
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection() throws Exception {
return dataSource.getConnection();
}
}
- 编写JavaBean
public class BeanStudent {
//JavaBean注意事项:将属性名设置和数据框表中的字段相同,方便提取表中的数据,否则还需要转一次,通过映射。
private int studentid;
private String studentname;
public BeanStudent(int studentid, String studentname) {
this.studentid = studentid;
this.studentname = studentname;
}
public int getStudentid() {
return studentid;
}
public void setStudentid(int studentid) {
this.studentid = studentid;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
@Override
public String toString() {
return "BeanStudent{" +
"studentid=" + studentid +
", studentname='" + studentname + '\'' +
'}';
}
}
- 实现增删改查的功能
public class DBUtilsTest {
//记得释放资源
public static void main(String[] args) throws Exception {
Connection connection = DBUtils.getConnection();
DataSource dataSource = DBUtils.getDataSource();
delete(connection);
}
//插入数据
public static void insert(Connection connection) throws Exception {
//QuerRunner的构造方法没有传入参数,调用update和query方法时参数中需要有Connection对象
QueryRunner queryRunner = new QueryRunner();
//?相当于是一个占位符 代表传入的值
String sql = "insert into student values (?,?)";
//要传入的数组
Object[] params = {8,"lbc"};
//方法的重载,因为前面QueryRunner是无参的,所以这里需要Connection参数
queryRunner.update(connection,sql,params);
DbUtils.close(connection);
}
//查询所有数据
public static void selectAll(DataSource dataSource) throws Exception {
//QueryRunner传入了DataSource对象
QueryRunner queryRunner = new QueryRunner(dataSource);
String sql = "select * from student";
//将结果集中的每一行数据都封装到一个对应的JavaBean实例中,再存放在List中
BeanListHandler<BeanStudent> beanStudentBeanListHandler = new BeanListHandler<>(BeanStudent.class);
//执行SQL语句,将结果存在BeanListHandler对象中
List<BeanStudent> list = queryRunner.query(sql, beanStudentBeanListHandler);
for (BeanStudent student:list){
System.out.println(student);
}
}
//更新数据
//代码的意思和插入差不多相同
public static void update(Connection connection) throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "update student set studentname=? where studentid =?";
Object[] params={"lhj",8};
queryRunner.update(connection,sql,params);
DbUtils.close(connection);
}
//删除数据
public static void delete(Connection connection) throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "delete from student where studentname=? and studentid = ?";
Object[] params = {"lhj",8};
queryRunner.update(connection,sql,params);
DbUtils.close(connection);
}
}