4. 案例-使用 Statement 完成 JDBC 增删改查

4. 案例-使用 Statement 完成 JDBC 增删改查

前言

在前面的章节中,我们已经懂得如何获取数据库连接 以及 单元测试,下面我们来使用 Statement 来实现 JDBC 的增删查改。

案例-增删改查练习

1.需求

  • 使用JDBC完成增删改查练习

2.步骤

  1. 注册驱动
  2. 获得连接
  3. 创建执行sql语句对象
  4. 执行sql语句, 处理结果
  5. 释放资源

3.实现

3.1 准备提供操作的数据库表

首先准备提供操作的 testdb 数据库 以及 user 数据表,如下:

MySQLuse testdb
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> 
mysql> show tables;
+------------------+
| Tables_in_testdb |
+------------------+
| t_user           |
| user             |
+------------------+
2 rows in set (0.00 sec)

mysql> 
mysql> select * from t_user;
+----+-------+------+------+
| id | uname | age  | sex  |
+----+-------+------+------+
|  1 | zs    |   18 |    1 |
|  2 | ls    |   20 |    0 |
|  3 | ww    |   23 |    1 |
|  4 | zl    |   24 |    1 |
|  5 | lq    |   15 |    0 |
|  6 | hh    |   12 |    0 |
|  7 | wzx   |   60 | NULL |
|  8 | lb    | NULL | NULL |
+----+-------+------+------+
8 rows in set (0.00 sec)

mysql> 

3.2 创建 CRUDDemo 类,并且编写单元测试:获取数据库连接

4. 案例-使用 Statement 完成 JDBC 增删改查
image-20210119223053506
public class CRUDDemo {

    /**
     * 获取数据库连接(使用ResourceBundle读取配置文件)
     */

    @Test
    public void test01() throws Exception {
        //1.使用ResourceBundle读取jdbc.properties文件中的内容
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");// 注意不用写 properties 后缀

        //2.读取配置信息
        String username = bundle.getString("jdbc.username");
        String password = bundle.getString("jdbc.password");
        String url = bundle.getString("jdbc.url");
        String driverClass = bundle.getString("jdbc.driverClass");

        System.out.println("username=" + username + ", password=" + password + ", url=" + url + ", driverClass=" + driverClass);

        //3.加载驱动
        Class.forName(driverClass);

        //4.获取连接
        Connection conn = DriverManager.getConnection(url,username,password);
        System.out.println(conn);
    }

}

其中配置文件 jdbc.properties 如下:

jdbc.username=root
jdbc.password=L***********0
jdbc.url=jdbc:mysql://localhost:3306/testdb?rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.driverClass=com.mysql.jdbc.Driver

3.3 使用 Statement  完成数据插入

4. 案例-使用 Statement 完成 JDBC 增删改查
image-20210119223805860
/**
 * 使用 Statement  完成数据插入
 * @throws Exception
 */

@Test
public void test02() throws Exception {
    //1.使用ResourceBundle读取jdbc.properties文件中的内容
    ResourceBundle bundle = ResourceBundle.getBundle("jdbc");// 注意不用写 properties 后缀

    //2.读取配置信息
    String username = bundle.getString("jdbc.username");
    String password = bundle.getString("jdbc.password");
    String url = bundle.getString("jdbc.url");
    String driverClass = bundle.getString("jdbc.driverClass");

    System.out.println("username=" + username + ", password=" + password + ", url=" + url + ", driverClass=" + driverClass);

    //3.加载驱动
    Class.forName(driverClass);

    //4.获取连接
    Connection conn = DriverManager.getConnection(url,username,password);
    System.out.println(conn);

    //5.使用 Statement  完成数据插入
    //5.1 创建执行sql语句对象
    Statement statement = conn.createStatement(); // 获取 Statement
    //5.2 编写SQL语句:插入一条user数据
    String sql = " insert into t_user values(null,'特朗普','68','0')";
    int rows = statement.executeUpdate(sql);
    System.out.println("几行收影响=" + rows);

    //5.释放资源
    statement.close();
    conn.close();
}

下面我们到数据库,查询看看插入的数据,如下:

mysql> select * from t_user;
+----+-----------+------+------+
| id | uname     | age  | sex  |
+----+-----------+------+------+
|  1 | zs        |   18 |    1 |
|  2 | ls        |   20 |    0 |
|  3 | ww        |   23 |    1 |
|  4 | zl        |   24 |    1 |
|  5 | lq        |   15 |    0 |
|  6 | hh        |   12 |    0 |
|  7 | wzx       |   60 | NULL |
|  8 | lb        | NULL | NULL |
|  9 | 特朗普    |   68 |    0 |  --- 插入的数据
+----+-----------+------+------+
9 rows in set (0.00 sec)

mysql> 

3.4 使用 Statement  完成数据更新

4. 案例-使用 Statement 完成 JDBC 增删改查
image-20210119224619248
    /**
     * 使用 Statement  完成数据更新
     * @throws Exception
     */

    @Test
    public void test03() throws Exception {
        //1.使用ResourceBundle读取jdbc.properties文件中的内容
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");// 注意不用写 properties 后缀

        //2.读取配置信息
        String username = bundle.getString("jdbc.username");
        String password = bundle.getString("jdbc.password");
        String url = bundle.getString("jdbc.url");
        String driverClass = bundle.getString("jdbc.driverClass");
//        System.out.println("username=" + username + ", password=" + password + ", url=" + url + ", driverClass=" + driverClass);

        //3.加载驱动
        Class.forName(driverClass);

        //4.获取连接
        Connection conn = DriverManager.getConnection(url,username,password);
        System.out.println(conn);

        //5.使用 Statement  完成数据插入
        //5.1 创建执行sql语句对象
        Statement statement = conn.createStatement(); // 获取 Statement
        //5.2 编写SQL语句:更新user数据
        String sql = " update t_user set uname='拜登', age=68 where id = 9 ";
        int rows = statement.executeUpdate(sql);
        System.out.println("几行收影响=" + rows);

        //5.释放资源
        statement.close();
        conn.close();
    }

再回到数据库,查看更新的数据如下:

mysql> select * from t_user;
+----+--------+------+------+
| id | uname  | age  | sex  |
+----+--------+------+------+
|  1 | zs     |   18 |    1 |
|  2 | ls     |   20 |    0 |
|  3 | ww     |   23 |    1 |
|  4 | zl     |   24 |    1 |
|  5 | lq     |   15 |    0 |
|  6 | hh     |   12 |    0 |
|  7 | wzx    |   60 | NULL |
|  8 | lb     | NULL | NULL |
|  9 | 拜登   |   68 |    0 | --- 更新的数据
+----+--------+------+------+
9 rows in set (0.00 sec)

mysql> 

3.5 使用 Statement  完成数据删除

4. 案例-使用 Statement 完成 JDBC 增删改查
image-20210119225154893
    /**
     * 使用 Statement  完成数据删除
     * @throws Exception
     */

    @Test
    public void test04() throws Exception {
        //1.使用ResourceBundle读取jdbc.properties文件中的内容
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");// 注意不用写 properties 后缀

        //2.读取配置信息
        String username = bundle.getString("jdbc.username");
        String password = bundle.getString("jdbc.password");
        String url = bundle.getString("jdbc.url");
        String driverClass = bundle.getString("jdbc.driverClass");
//        System.out.println("username=" + username + ", password=" + password + ", url=" + url + ", driverClass=" + driverClass);

        //3.加载驱动
        Class.forName(driverClass);

        //4.获取连接
        Connection conn = DriverManager.getConnection(url,username,password);
        System.out.println(conn);

        //5.使用 Statement  完成数据插入
        //5.1 创建执行sql语句对象
        Statement statement = conn.createStatement(); // 获取 Statement
        //5.2 编写SQL语句:删除user数据
        String sql = " delete from t_user where id = 9 ";
        int rows = statement.executeUpdate(sql);
        System.out.println("几行收影响=" + rows);

        //5.释放资源
        statement.close();
        conn.close();
    }

再到数据库中,查看删除的数据,如下:

mysql> select * from t_user;
+----+--------+------+------+
| id | uname  | age  | sex  |
+----+--------+------+------+
|  1 | zs     |   18 |    1 |
|  2 | ls     |   20 |    0 |
|  3 | ww     |   23 |    1 |
|  4 | zl     |   24 |    1 |
|  5 | lq     |   15 |    0 |
|  6 | hh     |   12 |    0 |
|  7 | wzx    |   60 | NULL |
|  8 | lb     | NULL | NULL |
|  9 | 拜登   |   68 |    0 | -- 删除之前的数据
+----+--------+------+------+
9 rows in set (0.00 sec)

mysql> 
mysql> 
mysql> select * from t_user;
+----+-------+------+------+
| id | uname | age  | sex  |
+----+-------+------+------+
|  1 | zs    |   18 |    1 |
|  2 | ls    |   20 |    0 |
|  3 | ww    |   23 |    1 |
|  4 | zl    |   24 |    1 |
|  5 | lq    |   15 |    0 |
|  6 | hh    |   12 |    0 |
|  7 | wzx   |   60 | NULL |
|  8 | lb    | NULL | NULL |
+----+-------+------+------+ -- 数据被删除了
8 rows in set (0.00 sec)

mysql> 

3.6 使用 Statement  完成一条数据查询

4. 案例-使用 Statement 完成 JDBC 增删改查
image-20210119225922790
/**
 * 使用 Statement  完成一条数据的查询
 *
 * @throws Exception
 */

@Test
public void test05() throws Exception {
    //1.使用ResourceBundle读取jdbc.properties文件中的内容
    ResourceBundle bundle = ResourceBundle.getBundle("jdbc");// 注意不用写 properties 后缀

    //2.读取配置信息
    String username = bundle.getString("jdbc.username");
    String password = bundle.getString("jdbc.password");
    String url = bundle.getString("jdbc.url");
    String driverClass = bundle.getString("jdbc.driverClass");

    //3.加载驱动
    Class.forName(driverClass);

    //4.获取连接
    Connection conn = DriverManager.getConnection(url, username, password);
    System.out.println(conn);

    //5.使用 Statement  完成数据插入
    //5.1 创建执行sql语句对象
    Statement statement = conn.createStatement(); // 获取 Statement
    //5.2 编写SQL语句:一条数据的查询
    String sql = " select * from t_user where id = 8 ";
    ResultSet resultSet = statement.executeQuery(sql);

    while (resultSet.next()) {
        //每遍历一次,就是一条数据
        // 打印查询的数据
        System.out.println("id=" + resultSet.getInt("id")
                + ", uname=" + resultSet.getString("uname")
                + ", age=" + resultSet.getString("age")
                + ", sex=" + resultSet.getString("sex"));
    }

    //5.释放资源
    statement.close();
    conn.close();
}

在上面的代码中,我们已经查询出了数据,但是并没有比较好的保存数据。

一般这种数据的查询,我们会编写一个保存的 pojo类。

3.7 编写 pojo 包下的 user 类,用来保存 t_user 表查询的数据

4. 案例-使用 Statement 完成 JDBC 增删改查
image-20210119231259396
package com.pojo;

import Java.io.Serializable;

/**
 * @author Aron.li
 * @date 2021/1/19 23:04
 */

public class User implements Serializable {

    /**
     * 成员属性
     * id
     * uname
     * age
     * sex
     */

    private Integer id;
    private String uname;
    private String age;
    private String sex;

    public User() {
    }

    public User(Integer id, String uname, String age, String sex) {
        this.id = id;
        this.uname = uname;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", uname='" + uname + ''' +
                ", age='" + age + ''' +
                ", sex='" + sex + ''' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

3.8 使用 user 类保存 Statement  查询的一条数据

4. 案例-使用 Statement 完成 JDBC 增删改查
image-20210119231417656
/**
 * 使用 Statement  完成一条数据的查询
 *
 * @throws Exception
 */

@Test
public void test05() throws Exception {
    //1.使用ResourceBundle读取jdbc.properties文件中的内容
    ResourceBundle bundle = ResourceBundle.getBundle("jdbc");// 注意不用写 properties 后缀

    //2.读取配置信息
    String username = bundle.getString("jdbc.username");
    String password = bundle.getString("jdbc.password");
    String url = bundle.getString("jdbc.url");
    String driverClass = bundle.getString("jdbc.driverClass");

    //3.加载驱动
    Class.forName(driverClass);

    //4.获取连接
    Connection conn = DriverManager.getConnection(url, username, password);
    System.out.println(conn);

    //5.使用 Statement  完成数据插入
    //5.1 创建执行sql语句对象
    Statement statement = conn.createStatement(); // 获取 Statement
    //5.2 编写SQL语句:一条数据的查询
    String sql = " select * from t_user where id = 8 ";
    ResultSet resultSet = statement.executeQuery(sql);

    User user = null// 创建 user 用来保存查询的数据
    while (resultSet.next()) {
        //每遍历一次,就是一条数据
        user = new User(
                resultSet.getInt("id"),
                resultSet.getString("uname"),
                resultSet.getString("age"),
                resultSet.getString("sex")
        );

    }

    // 打印结果
    System.out.println(user.toString());

    //5.释放资源
    statement.close();
    conn.close();
}

在上面我们已经成功查询了一条数据,并且以 User 类对象的方式保存了起来。

那么当我们需要查询多条数据的时候,该怎么操作呢?

3. 9 使用 ArrayList 保存 Statement  查询的多条数据

4. 案例-使用 Statement 完成 JDBC 增删改查
image-20210119231901721
/**
 * 使用 Statement  完成多条数据的查询
 *
 * @throws Exception
 */

@Test
public void test06() throws Exception {
    //1.使用ResourceBundle读取jdbc.properties文件中的内容
    ResourceBundle bundle = ResourceBundle.getBundle("jdbc");// 注意不用写 properties 后缀

    //2.读取配置信息
    String username = bundle.getString("jdbc.username");
    String password = bundle.getString("jdbc.password");
    String url = bundle.getString("jdbc.url");
    String driverClass = bundle.getString("jdbc.driverClass");

    //3.加载驱动
    Class.forName(driverClass);

    //4.获取连接
    Connection conn = DriverManager.getConnection(url, username, password);
    System.out.println(conn);

    //5.使用 Statement  完成数据插入
    //5.1 创建执行sql语句对象
    Statement statement = conn.createStatement(); // 获取 Statement
    //5.2 编写SQL语句:多条数据的查询
    String sql = " select * from t_user";
    ResultSet resultSet = statement.executeQuery(sql);

    // 用来保存多个user查询数据
    ArrayList<User> users = new ArrayList<>();
    while (resultSet.next()) {
        //每遍历一次,就是一条数据
        User user = new User(
                resultSet.getInt("id"),
                resultSet.getString("uname"),
                resultSet.getString("age"),
                resultSet.getString("sex")
        );
        //将查询的数据加入到 ArrayList 中
        users.add(user);
    }

    // 遍历查询结果
    for (User user : users) {
        System.out.println(user);
    }

    //5.释放资源
    resultSet.close();
    statement.close();
    conn.close();
}

4.小结

  1. 步骤
    • 注册驱动
    • 获得连接
    • 创建执行sql语句对象
    • 执行sql语句, 处理结果
    • 释放资源
  2. 发现练习里面的代码大部分都是重复的, 所以应该抽取


原文始发于微信公众号(海洋的渔夫):4. 案例-使用 Statement 完成 JDBC 增删改查

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/33911.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!