欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Dbutils工具类的使用

程序员文章站 2022-11-08 20:46:52
一、什么是Dbutils? Commons DbUtils是Apache组织提供的一个对JDBC进行简单封装的开源工具类库,使用它能够简化JDBC应用程序的开发,同时也不会影响程序的性能。来源百度百科 简而言之,Dbutils就是封装了jdbc的代码,简化了jdbc的dao层的操作。 二、Dbuti ......

一、什么是dbutils?

  commons dbutils是apache组织提供的一个对jdbc进行简单封装的开源工具类库,使用它能够简化jdbc应用程序的开发,同时也不会影响程序的性能。来源百度百科

  简而言之,dbutils就是封装了jdbc的代码,简化了jdbc的dao层的操作。

二、dbutils的使用

a:导入相关的依赖jar包

  • mysql-connector-java-5.1.7-bin.jar
  • commons-dbutils-1.7.jar

b:项目结构

Dbutils工具类的使用

  • studentdao接口:对student实体类对象操作的接口,使用接口利于维护
  • studentdaoimpl:studentdao接口的实现类,用于写具体的功能实现代码
  • student类:学生实体类对象,用于封装学生对象的相关属性信息
  • test类:功能测试类,用于测试功能实现的代码
  • jdbctools:对于jdbc的初步封装的工具类,用于获取数据库连接以及释放资源等操作
  • db-config.properties文件:用于存储数据库的连接的一些信息,防止硬编码格式,方便更改

 c:使用dbutils的具体步骤

  a:创建queryrunner对象 

 

queryrunner queryrunner = new queryrunner();

 

  b:调用queryrunner对象的方法执行相关操作,给queryrunner对象传递参数:connection,sql,具体的;,条件参数

 

public void insert(student student) {
        sql = "insert into student(name,clazz,grade) values(?,?,?)";
        try {
            //jdbctools.getconnection():数据库连接
            //sql:数据库查询sql语句
            //student.getname():需要的参数,参数与sql中的参数的数量保持一致
            queryrunner.update(jdbctools.getconnection(),sql,student.getname(),student.getclazz(),student.getgrade());
        } catch (sqlexception e) {
            e.printstacktrace();
        }
    }
public student findbyid(int id) {
        sql = " select * from student where id = ?";
        student student = null;
        try {
            student = queryrunner.query(jdbctools.getconnection(),sql,new beanhandler<student>(student.class),id);
        } catch (sqlexception e) {
            e.printstacktrace();
        }
        return student;
    }

策略对象

  • beanhandler:把单行的结果集封装成javabean对象,返回值是resultsethandler,该方法用于将单行结果集封装成javabean对象,对象是通过反射完成创建的
resultsethandler<javabean类型> rsh = new beanhandler<javabean类型>(javabean.class);
  • beanlisthandler:将多行结果集封装成对象,并将对象添加到list集合中
 list<javabean类型> list = <list<javabean类型>> new beanlisthandler<javabean类型>(javabean.class);
  • maphandler:将单行的结果集封装到一个map集合中,map集合中的建是表中的列名称,值对应表的列值。
map <string,object> map = new maphandler();
  • maplisthandler:用于多行结果集的处理,把每行的结果封装成一个map,最后把所有的map都放到一个集合中,返回的是一个list集合,list集合中存放的是map集合。
  list<map<string,object>> listmap = new maplisthandler();
  • columnhandler:本方法用于互殴去单列,单行或者多行的数据
list<object> namelist = new columnhandler();
  • scalarhandler:用户处理单行、单列的数据,多用于聚合函数的查询。注意:当聚合函数涉及到数字类型的时候,要注意返回值类型的转换,若使用integer或者long类型的时候,容易出现数据无法存储的时候,所以使用number(这个是所有数字数据类型的父类),对外提供了number.intvalue()和number.longvalue()等方法。

 

resultsethandler resultsethandler = new scalarhandler();

 

c:具体的实现代码

  a:javabean对象

package com.dreambamboo.entity;

public class student {
    private int id;
    private string name;
    private string grade;
    private string clazz;

    public student(int id, string name, string grade, string clazz) {
        this.id = id;
        this.name = name;
        this.grade = grade;
        this.clazz = clazz;
    }

    public student() {
    }

    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;
    }

    public string getgrade() {
        return grade;
    }

    public void setgrade(string grade) {
        this.grade = grade;
    }

    public string getclazz() {
        return clazz;
    }

    public void setclazz(string clazz) {
        this.clazz = clazz;
    }

    public student(string name, string grade, string clazz) {
        this.name = name;
        this.grade = grade;
        this.clazz = clazz;
    }

    @override
    public string tostring() {
        return "student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", grade='" + grade + '\'' +
                ", clazz='" + clazz + '\'' +
                '}';
    }
}

  b:dao接口

package com.dreambamboo.dao;

import com.dreambamboo.entity.student;

import java.util.list;


public interface studentdao {
    /**
     * 添加学生信息
     * @param student
     */
    public void insert(student student);

    /**
     * 更新学生信息
     * @param student
     */
    public void update(student student);

    /**
     * 删除学生信息
     * @param id
     */
    public void delete(int id);

    /**
     * 根据学生编号查询学生信息
     * @param id
     * @return
     */
    public student findbyid(int id);

    /**
     * 查询所有学生信息
     * @return
     */
    public list<student> findall();

    /**
     * 查询学生总数
     * @return
     */
    public int studentcount();
}

  c:dao接口实现类

package com.dreambamboo.dao.impl;

import com.dreambamboo.dao.studentdao;
import com.dreambamboo.entity.student;
import com.dreambamboo.util.jdbctools;
import org.apache.commons.dbutils.queryrunner;
import org.apache.commons.dbutils.resultsethandler;
import org.apache.commons.dbutils.handlers.beanhandler;
import org.apache.commons.dbutils.handlers.beanlisthandler;
import org.apache.commons.dbutils.handlers.scalarhandler;

import java.sql.sqlexception;
import java.util.list;

public class studentdaoimpl implements studentdao {
    private queryrunner queryrunner = null;//查询运行器
    public studentdaoimpl(){
        queryrunner = new queryrunner();
    }
    string sql = null;
    @override
    public void insert(student student) {
        sql = "insert into student(name,clazz,grade) values(?,?,?)";
        try {
            //jdbctools.getconnection():数据库连接
            //sql:数据库查询sql语句
            //student.getname():需要的参数,参数与sql中的参数的数量保持一致
            queryrunner.update(jdbctools.getconnection(),sql,student.getname(),student.getclazz(),student.getgrade());
        } catch (sqlexception e) {
            e.printstacktrace();
        }
    }

    @override
    public void update(student student) {
        sql = " update student set name = ? ,clazz = ?,grade = ? where id = ?";
        try {
            queryrunner.update(jdbctools.getconnection(),sql,student.getname(),student.getclazz(),student.getgrade(),student.getid());
        } catch (sqlexception e) {
            e.printstacktrace();
        }
    }

    @override
    public void delete(int id) {
        sql = "delete from student where id = ?";
        try {
            queryrunner.update(jdbctools.getconnection(),sql,id);
        } catch (sqlexception e) {
            e.printstacktrace();
        }
    }

    @override
    public student findbyid(int id) {
        sql = " select * from student where id = ?";
        student student = null;
        try {
            student = queryrunner.query(jdbctools.getconnection(),sql,new beanhandler<student>(student.class),id);
        } catch (sqlexception e) {
            e.printstacktrace();
        }
        return student;
    }

    @override
    public list<student> findall() {
        sql = "select * from student";
        list<student> list = null;
        try {
            list = queryrunner.query(jdbctools.getconnection(),sql,new beanlisthandler<>(student.class));
        } catch (sqlexception e) {
            e.printstacktrace();
        }
        return list;
    }
    @override
    public int studentcount() {
        sql = "select count(id) from student";
        int count = 0;
        try {
            count =  queryrunner.query(jdbctools.getconnection(),sql,new scalarhandler<integer>());

        } catch (sqlexception e) {
            e.printstacktrace();
        }
        return count;
    }
}

  d:数据库接口连接工具类

package com.dreambamboo.util;



import java.sql.*;
import java.util.resourcebundle;

/**
 * 数据库操作工具类
 */
public class jdbctools {
    private static string url;
    private static string username;
    private static string password;
    private static string driver;

    private static resourcebundle resourcebundle = resourcebundle.getbundle("com.dreambamboo.util.db-config");

    private jdbctools(){

    }

    /**
     * 使用静态代码块加载驱动程序
     *      防止重复代码,使用静态代码块在类加载的时候只会执行一次
     */
    static {
        url = resourcebundle.getstring("jdbc.url");
        username = resourcebundle.getstring("jdbc.username");
        password = resourcebundle.getstring("jdbc.password");
        driver = resourcebundle.getstring("jdbc.driver");
    }

    /**
     * 获取数据库连接
     * @return
     */
    public static connection getconnection(){
        connection connection = null;
        try {
            connection = drivermanager.getconnection(url,username,password);
        } catch (sqlexception e) {
            e.printstacktrace();
            system.out.println("获取连接失败");
        }
        return connection;
    }

    /**
     * 关闭数据库连接资源
     * @param connection    数据库连接
     * @param statement     数据库会话语句
     * @param resultset     数据库查询结果集
     */
    public static void release(connection connection, statement statement, resultset resultset){
        try {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultset != null) {
                resultset.close();
            }
        } catch (sqlexception e) {
            e.printstacktrace();
        }
    }

}

  e:数据库配置文件

jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=mysql
jdbc.driver=com.mysql.jdbc.driver

  f:测试代码

package com.dreambamboo.test;

import com.dreambamboo.dao.studentdao;
import com.dreambamboo.dao.impl.studentdaoimpl;
import com.dreambamboo.entity.student;

import java.util.list;

public class test {
    public static void main(string[] args) {
        studentdao studentdao = new studentdaoimpl();
        //studentdao.insert(new student("孙悟空","高三年级","五班"));
        //studentdao.update(new student(14,"孙悟空111","高三年级","十一班"));
        //studentdao.delete(14);
        list<student> list = studentdao.findall();
        for (student st : list) {
            system.out.println(st.getid() + "===>>>" + st.getname() + "===>>>>" + st.getclazz() + "===>>> "+ st.getgrade());
        }
    }
}

 三、自定义的dbutils工具类

a:接口结构图分析

Dbutils工具类的使用

 

Dbutils工具类的使用

b:自定义的策略对象

  • queryruuner的封装
package com.dreambamboo.utils;
import java.sql.*;

/**
 * @classname:queryutils
 * @description:自定义queryrunner中的(crud)增、删、改、查的方法
 */
public class queryutils {
    /**
     * @method:update
     * @description:所有实体的cud操作(create、update、delete)
     *      由于所有实体的cud操作代码基本相同,仅仅是操作执行的sql语句不同
     *      因此将实体的cud方法统一抽取成update方法
     * @param connection        数据库连接对象
     * @param sql               执行操作的sql语句
     * @param params            执行sql语句时的参数列表
     */
    public static void update(connection connection,string sql,object params[]){
        preparedstatement preparedstatement = null;
        resultset resultset = null;
        try {
            preparedstatement = connection.preparestatement(sql);
            for (int i = 0; i < params.length; i++) {
                preparedstatement.setobject(i+1,params[i]);
            }
            preparedstatement.executeupdate();
        } catch (sqlexception e) {
            e.printstacktrace();
        } finally {
            releaseutils.release(connection,preparedstatement,resultset);
        }
    }

    /**
     * @method:query
     * @description:所有实体的r(retrieve)读取查询操作
     *          实体的r操作,除了执行的sql语句不同,根据实体对象的不同,处理结果集的resultset的映射对象也不同
     *          因此在定义query方法时,可以将resultset的映射策略对象交由调用者提供,根据调用者提供的策略对象进行
     *          相对应的映射
     * @param connection        数据库连接对象
     * @param sql               执行的sql语句
     * @param params            执行sql语句时所需的参数列表
     * @param resultsethandler  调用者提供的策略对象
     * @return                  与调用者提供的策略对象相对应的映射对象
     */
    public static object query(connection connection,string sql, object params[], myresultsethandler resultsethandler){
        preparedstatement preparedstatement = null;
        resultset resultset = null;
        object object = null;
        try {
            preparedstatement = connection.preparestatement(sql);
            for (int i = 0; i < params.length; i++) {
                preparedstatement.setobject(i+1,params[i]);
            }
            resultset = preparedstatement.executequery();
            object = resultsethandler.handle(resultset);
        } catch (sqlexception e) {
            e.printstacktrace();
        } finally {
            releaseutils.release(connection, preparedstatement,resultset);
        }
        return object;
    }
}
  •  resultsethandler的封装
package com.dreambamboo.utils;

import java.sql.resultset;

/**
 * @classname:myresultsethandler
 * @description:结果集处理器接口
 */
public interface myresultsethandler {
    /**
     * @method:handler
     * @description:结果集处理方法
     * @param resultset 查询结果集
     * @return
     */
    public object handle(resultset resultset);
}
  • beanhandler的封装
    • 方式一
package com.dreambamboo.utils;

import org.apache.commons.dbutils.resultsethandler;

import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;
import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;

public class mybeanhandler implements resultsethandler {

    private class aclass;
    public mybeanhandler(class aclass) {
        this.aclass = aclass;
    }


    @override
    public object handle(resultset resultset) throws sqlexception {
        //结果集的结构
        resultsetmetadata resultsetmetadata = resultset.getmetadata();
        int size = resultsetmetadata.getcolumncount();
        object object = null;
        try {
            object = aclass.getconstructor().newinstance();
            if (resultset.next()){
                //根据结果集获取的操作
                //resultsetmetadata下标从1开始
                for (int i = 1; i <= size; i++) {
                    //mysql中的数据类型对应的javabean中的数据类型
                    string classname = resultsetmetadata.getcolumnclassname(i);
                    string columnname = resultsetmetadata.getcolumnname(i);
                    string methodname = "set" + columnname.substring(0,1).touppercase() + columnname.substring(1);
                    method method = null;
                    switch (classname){
                        case "java.lang.string":
                            string valuestr = resultset.getstring(columnname);
                            method = aclass.getmethod(methodname,string.class);
                            method.invoke(object,valuestr);
                            break;
                        case "java.lang.integer":
                            int valueint = resultset.getint(columnname);
                            method = aclass.getmethod(methodname,int.class);
                            method.invoke(object,valueint);
                            break;
                    }
                }
            }
        } catch (instantiationexception e) {
            e.printstacktrace();
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (invocationtargetexception e) {
            e.printstacktrace();
        } catch (nosuchmethodexception e) {
            e.printstacktrace();
        }
        return object;
    }
}
    • 方式二
package com.dreambamboo.utils;


import java.lang.reflect.field;
import java.sql.connection;
import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;

/**
 * @classname:
 * @description:将结果集封装成javabean对象
 * @author:dreambamboo
 */
public class javabeanhandler implements myresultsethandler {
    private class  clazz;
    public javabeanhandler(class clazz){
        this.clazz = clazz;
    }
    @override
    public object handle(resultset resultset) {
        object bean = null;
        object value = null;
        try {
            if (!resultset.next()) {
                return null;
            }
            bean = clazz.newinstance();
            //获取结果集的元数据
            resultsetmetadata resultsetmetadata = resultset.getmetadata();
            //获取结果集的总数
            int size = resultsetmetadata.getcolumncount();
            for (int i = 0; i < size; i++) {
                //获取元数据的列名称
                string columnname = resultsetmetadata.getcolumnname(i+1);
                value = resultset.getobject(i+1);
                //反射出类上列名对应的属性
                field field = clazz.getdeclaredfield(columnname);
                field.setaccessible(true);
                field.set(bean,value);
            }
        } catch (sqlexception e) {
            e.printstacktrace();
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (instantiationexception e) {
            e.printstacktrace();
        } catch (nosuchfieldexception e) {
            e.printstacktrace();
        }
        return bean;
    }
}
  • beanlisthandler的封装
    • 方式一
package com.dreambamboo.utils;

import org.apache.commons.dbutils.resultsethandler;

import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;
import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;
import java.util.arraylist;
import java.util.list;

public class mybeanlisthandler implements resultsethandler {
    private class aclass;
    public mybeanlisthandler(class aclass){
        this.aclass = aclass;
    }
    @override
    public object handle(resultset resultset) throws sqlexception {
        resultsetmetadata resultsetmetadata = resultset.getmetadata();
        list list = new arraylist();
        int size = resultsetmetadata.getcolumncount();
        object object = null;
        while (resultset.next()){
            try {
                object = aclass.getconstructor().newinstance();
                for (int i = 1; i <= size; i++) {
                    string classname = resultsetmetadata.getcolumnclassname(i);
                    string columnname = resultsetmetadata.getcolumnname(i);
                    string methodname = "set" + columnname.substring(0,1).touppercase() + columnname.substring(1);
                    method method = null;
                    object value = null;
                    switch (classname){
                        case "java.lang.string":
                            value = resultset.getstring(i);
                            method = aclass.getmethod(methodname,string.class);
                            break;
                        case "java.lang.integer":
                            value = resultset.getint(i);
                            method = aclass.getmethod(methodname,int.class);
                            break;
                    }
                    method.invoke(object,value);
                }
                list.add(object);
            } catch (instantiationexception e) {
                e.printstacktrace();
            } catch (illegalaccessexception e) {
                e.printstacktrace();
            } catch (invocationtargetexception e) {
                e.printstacktrace();
            } catch (nosuchmethodexception e) {
                e.printstacktrace();
            }

        }
        return list;
    }
}
    • 方式二
package com.dreambamboo.utils;

import java.lang.reflect.field;
import java.sql.connection;
import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;
import java.util.arraylist;
import java.util.list;

/**
 * @classname:listhandler
 * @description:将结果集封装成list对象
 */
public class listhandler implements myresultsethandler {
    private class<?> clazz;
    public listhandler(class clazz){
        this.clazz = clazz;
    }
    @override
    public object handle(resultset resultset) {
        list<object> list = new arraylist<>();
        object bean = null;
        field field = null;
        try {
            while (resultset.next()){
                bean = clazz.newinstance();
                resultsetmetadata resultsetmetadata = resultset.getmetadata();
                int size = resultsetmetadata.getcolumncount();
                for (int i = 0; i < size; i++) {
                    string columnname = resultsetmetadata.getcolumnname(i+1);
                    object value = resultset.getobject(i+1);
                    field = bean.getclass().getdeclaredfield(columnname);
                    field.setaccessible(true);
                    field.set(bean,value);
                }
                list.add(bean);
            }
        } catch (sqlexception e) {
            e.printstacktrace();
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (instantiationexception e) {
            e.printstacktrace();
        } catch (nosuchfieldexception e) {
            e.printstacktrace();
        } finally {
        }
        return  list;
    }
}
  • beanmaphandler的封装
    • 方式一
package com.dreambamboo.utils;

import com.sun.org.apache.bcel.internal.generic.ret;
import org.apache.commons.dbutils.resultsethandler;

import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;
import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;
import java.util.hashmap;
import java.util.map;

public class mymaphandler implements resultsethandler {
    private class aclass;
    public mymaphandler(class aclass){
        this.aclass =aclass;
    }
    @override
    public map<integer, object> handle(resultset resultset) throws sqlexception {
        resultsetmetadata resultsetmetadata = resultset.getmetadata();
        int size = resultsetmetadata.getcolumncount();
        map<integer,object> map = new hashmap<>();
        object value = null;
        object object = null;
        string columnname = null;
        method method  = null;
        string methodname = null;
        string classname = null;
        int id = 0;
        try {
            if (resultset.next()){
                object = aclass.getconstructor().newinstance();
                for (int i = 1; i <= size; i++) {
                    classname = resultsetmetadata.getcolumnclassname(i);
                    columnname = resultsetmetadata.getcolumnname(i);
                    methodname = "set" + columnname.substring(0,1).touppercase() + columnname.substring(1);
                    if (columnname.equals("id")){
                        id = resultset.getint("id");
                    }
                    switch (classname){
                        case "java.lang.string":
                            value = resultset.getstring(i);
                            method =aclass.getmethod(methodname,string.class);
                            break;
                        case "java.lang.integer":
                            value = resultset.getint(i);
                            method = aclass.getmethod(methodname,int.class);
                            break;
                    }
                    method.invoke(object,value);
                }
            }
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (invocationtargetexception e) {
            e.printstacktrace();
        } catch (nosuchmethodexception e) {
            e.printstacktrace();
        } catch (instantiationexception e) {
            e.printstacktrace();
        }
        map.put(id,object);
        return map;
    }

}
    • 方式二
package com.dreambamboo.utils;

import java.lang.reflect.field;
import java.security.privatekey;
import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;
import java.util.hashmap;
import java.util.map;

public class maphandler implements myresultsethandler {
    private class<?> clazz;
    public maphandler(class clazz){
        this.clazz = clazz;
    }
    @override
    public object handle(resultset resultset) {
        map<string,object> map = new hashmap<>();
        object bean = null;
        field field = null;
        string idstr = null;
        try {
            while (resultset.next()){
                bean = clazz.newinstance();
                resultsetmetadata resultsetmetadata = resultset.getmetadata();
                int size = resultsetmetadata.getcolumncount();
                for (int i = 0; i < size; i++) {
                    string columnname = resultsetmetadata.getcolumnname(i+1);
                    if ("id".equals(columnname)){
                        idstr = string.valueof(resultset.getobject(columnname));
                    }
                    object value = resultset.getobject(i+1);
                    field = bean.getclass().getdeclaredfield(columnname);
                    field.setaccessible(true);
                    field.set(bean,value);
                }
                map.put(idstr,bean);
            }
        } catch (sqlexception e) {
            e.printstacktrace();
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (instantiationexception e) {
            e.printstacktrace();
        } catch (nosuchfieldexception e) {
            e.printstacktrace();
        }
        return map;
    }
}
  • maplisthandler的封装
    • 方式一
package com.dreambamboo.utils;

import org.apache.commons.dbutils.resultsethandler;

import javax.jws.oneway;
import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;
import java.util.arraylist;
import java.util.hashmap;
import java.util.list;
import java.util.map;

public class mymaplisthandler implements resultsethandler {

    @override
    public object handle(resultset resultset) throws sqlexception {
        resultsetmetadata resultsetmetadata = resultset.getmetadata();
        int size = resultsetmetadata.getcolumncount();
        list<map<string,object>> list = new arraylist<>();
        object object = null;
        map<string,object> map = null;
        while (resultset.next()){
            map = new hashmap<>();
            for (int i = 1; i <= size; i++) {
                string columnclass = resultsetmetadata.getcolumnclassname(i);
                string columnname = resultsetmetadata.getcolumnname(i);
                switch (columnclass){
                    case "java.lang.string":
                        object = resultset.getstring(i);
                        break;
                    case "java.lang.integer":
                        object = resultset.getint(i);
                        break;
                }
                map.put(columnname, object);
                list.add(map);
            }
         }
        return list;
    }
}
  • 方式二
package com.dreambamboo.utils;

import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;
import java.util.arraylist;
import java.util.hashmap;
import java.util.list;
import java.util.map;

public class maplisthandler implements myresultsethandler {
    @override
    public object handle(resultset resultset) {
        string columnname = null;
        object value = null;
        list<map<string,object>> list = new arraylist<>();
        try {
            while (resultset.next()){
                resultsetmetadata resultsetmetadata = resultset.getmetadata();
                int size = resultsetmetadata.getcolumncount();
                map<string,object> map = new hashmap<>();
                for (int i = 0; i < size; i++) {
                    columnname = resultsetmetadata.getcolumnname(i+1);
                    value = resultset.getobject(columnname);
                    map.put(columnname,value);
                }
                list.add(map);
            }
        } catch (sqlexception e) {
            e.printstacktrace();
        }

        return list;
    }
}

c:测试代码

a:basedao

package com.dreambamboo.dao;

import com.dreambamboo.entity.student;

import java.util.list;

public interface basedao {
    public void save(student student);
    public void delete(int id);
    public void update(student student);
    public student getbyid(int id);
    public list<student> getall();
}

b:basedaoimpl实现类

package com.dreambamboo.dao.impl;

import com.dreambamboo.dao.basedao;
import com.dreambamboo.entity.student;
import com.dreambamboo.utils.javabeanhandler;
import com.dreambamboo.utils.listhandler;
import com.dreambamboo.utils.queryutils;
import com.dreambamboo.utils.releaseutils;

import java.sql.connection;
import java.sql.sqlexception;
import java.util.arraylist;
import java.util.list;

public class basedaoimpl implements basedao {
    private connection connection = null;
    private string sql = null;
    private object[] params = null;
    @override
    public void save(student student) {
        try {
            connection = releaseutils.getconnection();
            sql = "insert into student(name,clazz,grade) values(?,?,?)";
            params = new object[]{student.getname(),student.getclazz(),student.getgrade()};
            queryutils.update(connection,sql,params);
        } catch (sqlexception e) {
            e.printstacktrace();
        } finally {
            releaseutils.release(connection,null,null);
        }
    }

    @override
    public void delete(int id) {
        try {
            connection = releaseutils.getconnection();
            sql = "delete from student where id = ?";
            params = new object[]{id};
            queryutils.update(connection,sql,params);
        } catch (sqlexception e) {
            e.printstacktrace();
        } finally {
            releaseutils.release(connection,null,null);
        }
    }

    @override
    public void update(student student) {
        try {
            connection = releaseutils.getconnection();
            sql = "update student set name = ?,clazz = ?, grade = ? where id = ?";
            params = new object[]{student.getname(),student.getclazz(),student.getgrade(),student.getid()};
            queryutils.update(connection,sql,params);
        } catch (sqlexception e) {
            e.printstacktrace();
        } finally {
            releaseutils.release(connection,null,null);
        }
    }

    @override
    public student getbyid(int id) {
        student student = null;
        try {
            connection = releaseutils.getconnection();
            sql = "select * from student where id = ?";
            params = new object[]{id};
            student = (student) queryutils.query(connection,sql,params,new javabeanhandler(student.class));

        } catch (sqlexception e) {
            e.printstacktrace();
        } finally {
            releaseutils.release(connection,null,null);
        }
        return student;
    }

    @override
    public list<student> getall() {
        list<student> list = null;
        try {
            connection = releaseutils.getconnection();
            list = new arraylist<>();
            sql = "select * from student";
            params = new object[]{};
            list = (list<student>) queryutils.query(connection,sql,params,new listhandler(student.class));
        } catch (sqlexception e) {
            e.printstacktrace();
        } finally {
            releaseutils.release(connection,null,null);
        }
        return list;
    }
}

c:测试类test

  • 测试添加代码
package com.dreambamboo.test;

import com.dreambamboo.dao.basedao;
import com.dreambamboo.dao.impl.basedaoimpl;
import com.dreambamboo.entity.student;

public class test03 {
    public static void main(string[] args) {
        basedao basedao = new basedaoimpl();
        basedao.save(new student("张三","六班","高三"));
    }
}
    • 运行效果

Dbutils工具类的使用

Dbutils工具类的使用

  • 测试更新代码
package com.dreambamboo.test;

import com.dreambamboo.dao.basedao;
import com.dreambamboo.dao.impl.basedaoimpl;
import com.dreambamboo.entity.student;

public class test03 {
    public static void main(string[] args) {
        basedao basedao = new basedaoimpl();
        student student = new student(13,"李四","gaosan","wuban");
        basedao.update(student);
    }
}
    • 运行结果

Dbutils工具类的使用

  • 测试删除代码
package com.dreambamboo.test;

import com.dreambamboo.dao.basedao;
import com.dreambamboo.dao.impl.basedaoimpl;

public class test03 {
    public static void main(string[] args) {
        basedao basedao = new basedaoimpl();
       basedao.delete(13);
    }
}
    • 运行结果

Dbutils工具类的使用

Dbutils工具类的使用

  • 测试查询代码
    • 查询单条记录
package com.dreambamboo.test;

import com.dreambamboo.dao.basedao;
import com.dreambamboo.dao.impl.basedaoimpl;
import com.dreambamboo.entity.student;


public class test03 {
    public static void main(string[] args) {
        basedao basedao = new basedaoimpl();
        student student = basedao.getbyid(14);
        system.out.println(student);
    }
}
      • 运行结果

Dbutils工具类的使用

    • 查询所有
package com.dreambamboo.test;

import com.dreambamboo.dao.basedao;
import com.dreambamboo.dao.impl.basedaoimpl;
import com.dreambamboo.entity.student;

import java.util.list;


public class test03 {
    public static void main(string[] args) {
        basedao basedao = new basedaoimpl();
        list<student> list = basedao.getall();
        for (student stu:list
             ) {
            system.out.println(stu);
        }
    }
}
      • 运行结果

Dbutils工具类的使用