采用Druid以及DButils简单连接数据库

一、简单介绍

首先导入三个jar包:
在这里插入图片描述

  1. mysql-connector-java-5.1.37-bin.jar:
    这个jar包就不细说了,MySQL数据库对Java.sql.Driver 接口的实现。
  2. druid-1.1.10.jar:
    Druid数据库连接池,用法与其他大部分连接池没有区别.
  3. commons-dbutils-1.3.jar:
    commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。

二、步骤

1. 创建数据表

这里只创建一个简单的数据表,只有四个字段:
girl表:
在这里插入图片描述

2. 根据数据表创建一个实体类:

package com.fseast.bean;

public class Girl {
    private int id;
    private String name;
    private String phone;
    private int bid;

    public Girl() {
        super();
    }

    public Girl(int id, String name, String phone, int bid) {
        super();
        this.id = id;
        this.name = name;
        this.phone = phone;
        this.bid = bid;
    }

    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 getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public int getBid() {
        return bid;
    }

    public void setBid(int bid) {
        this.bid = bid;
    }

    @Override
    public String toString() {
        return "Girl{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", bid=" + bid +
                '}';
    }
}

3. 编写配置文件

配置文件名为 druid.properties

#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
#url=jdbc:mysql://localhost:3306/mysqldb
username=root
password=123456
initialSize=10
minIdle=5
maxActive=20
maxWait=5000

4. 编写工具类

此类是jdbc的工具类,用于单独创建连接:
包含有连接方法方法。
当然觉得这个工具类还可以加上CRUD的通用方法也可以自行加上,这里就写了创建连接的方法。

public class JDBCUtils {
    //声明一个静态私有属性
    private static DataSource dataSource;

    static {
        try {
            //1. 创建一个Properties对象
            Properties properties = new Properties();
            //2. 加载配置文件
            properties.load(
                    JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //3. 根据配置文件创建DataSource,这里用到了druid-1.1.10.jar
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //获取连接的方法
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    
   }

5. 进行CRUD操作

DButils操作数据库:
|------ QueryRunner可以实现jdbc中增删改查的大部分功能。
|----------- 使用两个方法实现大部分功能:
update(Connection connection,String sql,Object … params)
query(Connection connection,String sql)

当使用query方法时:
需要了解结果集处理ResultSetHandler接口,因为ResultSetHandler为query的一个形参类型。
ResultSetHandler接口的实现类:
BeanHandler 单个对象的处理器
BeanListHandLer 集合对象处理器
ScalarHandler 任意对象处理器 -----> Object

package com.fseast.jdbc2;

import com.fseast.bean.Girl;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Before;
import org.junit.Test;

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

public class DBUtilsTest {
    private QueryRunner queryRunner;
    private Connection connection;


//    直接在使用到这两个对象的方法里面实现这两个步骤也一样。
    @Before
    public void before() {
        queryRunner = new QueryRunner();
        connection = JDBCUtils.getConnection();
    }


    /*使用QueryRunner实现插入数据*/
    @Test
    public void inserTest() throws SQLException {
        queryRunner = new QueryRunner();
        String sql = "INSERT INTO girl VALUES(?,?,?,?)";
        int result = queryRunner.update(connection,sql,14,"测试2","5201314",null);

        System.out.println(result > 0?"插入成功":"插入失败");

    }

    /*使用QueryRunner 实现修改数据*/
    @Test
    public void deleteTest() throws SQLException {
        String sql = "DELETE FROM girl WHERE id = ?";
        int delete = queryRunner.update(connection, sql, 9);

        System.out.println(delete > 0 ? "删除成功" : "删除失败");
    }

    /*使用QueryRunner实现修改数据*/
    @Test
    public void updateTest() throws SQLException {
        String sql = "UPDATE girl SET id = ? WHERE id = ?";
        int result = queryRunner.update(connection, sql, 12, 1);
        System.out.println(result > 0 ? "修改成功" : "修改失败");

    }

    /*使用QueryRunner 实现查询单个对象数据
    * 单个对象使用ResultSetHandler子接口BeanHandler*/
    @Test
    public void selectSampleTest() throws SQLException {
        String sql = "SELECT * from girl WHERE id = ?";
        Girl girl = queryRunner.query(connection, sql, new BeanHandler<>(Girl.class), 13);
        System.out.println(girl);
    }

    /*使用QueryRunner 实现查询多个对象数据*/
    @Test
    public void selectListTest() throws SQLException {
        String sql = "SELECT * FROM girl";
        List<Girl> girlList = queryRunner.query(connection, sql, new BeanListHandler<Girl>(Girl.class));

        for (Girl girl : girlList){
            System.out.println(girl);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值