利用QueryRunner类实现对数据库的增删改查操作,需要先导入jar包:commons-dbutils-1.6。利用QueryRunner类可以实现对数据步骤的简化。

1、添加

运用JDBC工具类实现连接:

package JDBCUtils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    private static Connection con;
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {// 静态代码块只执行一次,获取一次信息即可
        try {
            readConfig();
            Class.forName(driver);
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception ex) {
            throw new RuntimeException("数据库连接失败");
        }
    }
/*
 * getClassLoader();返回该类的加载器
 * getResourceAsStream();查找具有给定名称的资源
 */
    private static void readConfig() {
        InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("JDBC.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = pro.getProperty("driver");
        url = pro.getProperty("url");
        username = pro.getProperty("username");
        password = pro.getProperty("password");
    }

    public static Connection getConnection() {
        return con;
    }
    public static void close(Connection con) {

        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("con流关闭异常!");
            }
        }

    }
    public static void close(Connection con, Statement stat) {

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("stat流关闭异常!");
            }
        }

        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("con流关闭异常!");
            }
        }

    }

    public static void close(Connection con, Statement stat, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("rs流关闭异常!");
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("stat流关闭异常!");
            }
        }

        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("con流关闭异常!");
            }
        }

}
}
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;

import JDBCUtils.JDBCUtils;

public class add {

    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "INSERT INTO student(studentno,sname,sex,birthday,classno,point,phone,email) VALUES(?,?,?,?,?,?,?,?)";
            Object[] ", "Jack", "男", "1988-12-01",
                    ", "Tom.@3218n.com" };

            int num = qr.update(con, sql, params);
            System.out.println("添加了" + num + "行");

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con);
    }
}

2、删除

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;

import JDBCUtils.JDBCUtils;

public class DeleteDemo {
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "DELETE from Student where sname =?";
            Object[] delete = { "Tom" };
            qr.update(con, sql, delete);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con);
    }
}

3、修改

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;

import JDBCUtils.JDBCUtils;

public class UpdateDemo {
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "Update Student set classno=? Where sname='韩吟秋'";
            Object[] update = { " };
            qr.update(con, sql, update);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con);
    }
}

4、查询

(1)

ArrayHandler: 将结果集的第一行存储到Object[]数组中

ArrayListHandler: 将结果集的每一行存储到Object[]数组中

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;

import JDBCUtils.JDBCUtils;

public class SeleteDemo {
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "Select * from Student where studentno=?";
            Object[]  };
            List<Object[]> list = qr.query(con, sql, new ArrayListHandler(),
                    select);
            // 将记录封装到一个装有Object[]的List集合中
            for (Object[] arr : list) {
                System.out.println(Arrays.toString(arr));
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con);
    }

}

(2)

BeanHandler:结果集中第一条记录封装到一个指定的javaBean中。

BeanListHandler:结果集中每一条记录封装到javaBean中,再将javaBean封装到list集合中。

public class Student {
private String studentno;
private String sname;
private String sex;
private String birthday;
private String classno;
private String point;
private String phone;
private String email;
public String getStudentno() {
    return studentno;
}
public void setStudentno(String studentno) {
    this.studentno = studentno;
}
public String getSname() {
    return sname;
}
public void setSname(String sname) {
    this.sname = sname;
}
public String getSex() {
    return sex;
}
public void setSex(String sex) {
    this.sex = sex;
}
public String getBirthday() {
    return birthday;
}
public void setBirthday(String birthday) {
    this.birthday = birthday;
}
@Override
public String toString() {
    return "Student [studentno=" + studentno + ", sname=" + sname + ", sex="
            + sex + ", birthday=" + birthday + ", classno=" + classno
            + ", point=" + point + ", phone=" + phone + ", email=" + email
            + "]";
}
public String getClassno() {
    return classno;
}
public void setClassno(String classno) {
    this.classno = classno;
}
public String getPoint() {
    return point;
}
public void setPoint(String point) {
    this.point = point;
}
public String getPhone() {
    return phone;
}
public void setPhone(String phone) {
    this.phone = phone;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}

}
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import JDBCUtils.JDBCUtils;

public class SeleteDemo {
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "Select * from Student where studentno=?";
            Object[]  };
            List<Student> list = qr.query(con, sql,new BeanListHandler<Student>((Student.class)), select);
            // 将记录封装到一个装有Object[]的List集合中
            for (Student s : list) {
                System.out.println(s);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con);
    }

}

(3)ColumnListHandler将结果集中指定的列封装到List集合。

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

import JDBCUtils.JDBCUtils;

public class SeleteDemo {
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "Select * from Student where studentno=?";
            Object[] };
            List<String> list = qr.query(con, sql,new ColumnListHandler<String>(), select);
            // 将记录封装到一个装有Object[]的List集合中
            for (String str: list) {
                System.out.println(str);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con);
    }

}

查询学生的学号:

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

import JDBCUtils.JDBCUtils;

public class SeleteDemo {
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "Select studentno from Student  ";
            Object[] select = {};
            List<String> list = qr.query(con, sql,new ColumnListHandler<String>(), select);
            // 将记录封装到一个装有Object[]的List集合中
            for (String str: list) {
                System.out.println(str);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con);
    }

}

(4)ScalarHandler返回一个数据

import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import JDBCUtils.JDBCUtils;

public class SeleteDemo {
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "SELECT COUNT(sname)   FROM Student";
            Object[] select = {};
            long count= qr.query(con, sql, new ScalarHandler<Long>(), select);
            System.out.println(count);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con);
    }

}

(5)MapHandler:将结果集的第一行封装到Map集合中

MapListHandler:将结果集的多条记录封装到一个集合中

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import JDBCUtils.JDBCUtils;

public class SeleteDemo {
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = JDBCUtils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "Select studentno from Student  ";
            Object[] select = {};
            List<Map<String,Object>> list = qr.query(con, sql, new MapListHandler(),select);

            // 将记录封装到一个装有Object[]的List集合中
            for (Map<String,Object> map : list) {
                for(String key : map.keySet()){
                    System.out.print(key+"..."+map.get(key));
                }
                System.out.println();
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con);
    }

}

增删改查——DBUtils的更多相关文章

  1. dbutils中实现数据的增删改查的方法,反射常用的方法,绝对路径的写法(杂记)

    jsp的三个指令为:page,include,taglib... 建立一个jsp文件,建立起绝对路径,使用时,其他jsp文件导入即可 导入方法:<%@ include file="/c ...

  2. MySQL数据库学习笔记(十二)----开源工具DbUtils的使用(数据库的增删改查)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  3. mvc模式jsp+servel+dbutils oracle基本增删改查demo

    mvc模式jsp+servel+dbutils oracle基本增删改查demo 下载地址

  4. 开源工具DbUtils的使用(数据库的增删改查)

    开源工具DbUtils的使用(数据库的增删改查) 一.DbUtils简介: DBUtils是apache下的一个小巧的JDBC轻量级封装的工具包,其最核心的特性是结果集的封装,可以直接将查询出来的结果 ...

  5. Java Web(十) JDBC的增删改查,C3P0等连接池,dbutils框架的使用

    前面做了一个非常垃圾的小demo,真的无法直面它,菜的抠脚啊,真的菜,好好努力把.菜鸡. --WH 一.JDBC是什么? Java Data Base Connectivity,java数据库连接,在 ...

  6. python操作mysql数据库增删改查的dbutils实例

    python操作mysql数据库增删改查的dbutils实例 # 数据库配置文件 # cat gconf.py #encoding=utf-8 import json # json里面的字典不能用单引 ...

  7. 使用DbUtils实现增删改查——ResultSetHandler 接口的实现类

    在上一篇文章中<使用DbUtils实现增删改查>,发现运行runner.query()这行代码时.须要自己去处理查询到的结果集,比較麻烦.这行代码的原型是: public Object q ...

  8. Android 利用xUtils框架实现对sqllite的增删改查

    首先下载xUtils,下载地址:https://github.com/wyouflf/xUtils  把下载好的文件压缩,把里面的jar包拷进项目中如图所示: 这里新建一个User类进行测试增删改查 ...

  9. MySQL数据库学习笔记(十一)----DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

随机推荐

  1. 浅谈python中文件和文件夹的相关操作

    文件操作 文件的打开与关闭 打开文件 使用open(文件名,访问方式)函数,可以打开一个已存在的文件,或者创建一个新的文件. 示例如下: f = open('test.txt') # 访问方式可以省略 ...

  2. NOIP退役记

    10.10 想着自己再过一个月就要退役了,真叫人心酸.想到徐志摩的诗: "悄悄地,我走了,正如我悄悄的来,我挥一挥衣袖,不带走一片云彩." 学了这么久的OI,感觉真的就像诗里讲的一 ...

  3. AQS源码解析(一)-AtomicBoolean源码解析

    基本类: AtomicInteger AtomicLong AtomicBoolean 数组类型: AtomicIntegerArray AtomicLongArray AtomicReference ...

  4. freemarker导出复杂样式的Excel

    freemarker导出复杂样式的Excel 代码地址: gitee https://gitee.com/suveng/demo/tree/master/chapter.002 代码存放于demo下面 ...

  5. Windows上快捷登陆应用程序

    在Windows上有些程序双击后,还需要输入用户名密码等,填写很多信息后才开始使用. 有些程序本身实现了保存信息,或者可以自动登陆. 但也有些程序无信息保存和自动登陆功能,如果经常使用,每次都填写觉得 ...

  6. 阿里分布式事务seata入门(采坑)

    1. 阿里分布式事务seata入门(采坑) 1.1. 前言 seata是feascar改名而来,这是阿里在19年年初开源出来的分布式事务框架,当初刚出来的时候就想研究下了,一直拖到了现在,目前是0.8 ...

  7. ESXi安装报错,No network adapters were detected...

    转载请在文章开头附上原文链接地址:https://www.cnblogs.com/Sunzz/p/11438066.html 报错内容 No network adapters No Network a ...

  8. JavaScript 数据结构与算法之美 - 你可能真的不懂递归

    1. 前言 算法为王. 排序算法博大精深,前辈们用了数年甚至一辈子的心血研究出来的算法,更值得我们学习与推敲. 因为之后要讲有内容和算法,其代码的实现都要用到递归,所以,搞懂递归非常重要. 2. 定义 ...

  9. nginx有哪些作用

    Nginx应该是现在最火的web和反向代理服务器,没有之一.她是一款诞生于俄罗斯的高性能web服务器,尤其在高并发情况下,相较Apache,有优异的表现. 那除了负载均衡,她还有什么其他的用途呢,下面 ...

  10. HAOI2006 (洛谷P2341)受欢迎的牛 题解

    HAOI2006 (洛谷P2341)受欢迎的牛 题解 题目描述 友情链接原题 每头奶牛都梦想成为牛棚里的明星.被所有奶牛喜欢的奶牛就是一头明星奶牛.所有奶 牛都是自恋狂,每头奶牛总是喜欢自己的.奶牛之 ...