JDBC 9 步连接数据库

Java Database Connectivity

 

 

一、配置文件:

username = 用户名
password = 密码
jdbcURL = jdbc:mysql://192.168.1.2:3306/数据库名?useUnicode=true&useSSL=false&amp&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
jdbcDriver = com.mysql.cj.jdbc.Driver

 

 二、JDBC 9 步实现查询数据的操作:

package com.joyupx.jdbc;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC 执行步骤
 *
 * @作者 hapday
 * @author hapday
 * @时间 2023-04-17
 * @time 2023-04-17
 * @起始于 0.1.0
 * @since 0.1.0
 */
@Slf4j
public class JDBC_Step {

    @Test
    public void query_single () {
        /**
         * 第一步、获取数据库的配置
         */
        InputStream databaseConfigInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties") ; // 从【类路径】中获取配置文件
        Properties databaseConfigProperties = new Properties();
        try {
            databaseConfigProperties.load(databaseConfigInputStream);   // 加载【数据库】配置文件
        } catch (IOException e) {
            log.error("加载【数据库配置文件】失败!", e);

            return;
        }

        String username = databaseConfigProperties.getProperty("username");
        String password = databaseConfigProperties.getProperty("password");
        String jdbcURL = databaseConfigProperties.getProperty("jdbcURL");
        String jdbcDriver = databaseConfigProperties.getProperty("jdbcDriver");

        /**
         * 第二步、注册驱动
         */
        try {
            Class.forName(jdbcDriver);
        } catch (ClassNotFoundException e) {
            log.error("没有找到数据库的驱动!", e);

            return ;
        }

        /**
         * 第三步、获取数据库的连接
         */
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(jdbcURL, username, password);
        } catch (SQLException e) {
            log.error("获取 Java 程序与数据库服务端程序的连接对象 - 失败!", e);

            return ;
        }

        /**
         * 第四步、编写(与业务密切相关的)SQL。
         */
        String querySQL = "SELECT * FROM [`数据库名`].`artup_address`;";

        /**
         * 第五步、创建 SQL 的【预声明】对象,用于对 SQL 语句做准备工作。
         */
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(querySQL);
        } catch (SQLException e) {
            log.error("创建 SQL【预备声明】对象 - 失败!", e);

            return;
        }

        /**
         * 第六步、执行 SQL 并获取结果;具体到这里是执行查询操作并获取到结果集。
         */
        ResultSet resultSet = null;
        try {
            resultSet = preparedStatement.executeQuery(querySQL);
        } catch (SQLException e) {
            log.error("执行 SQL 查询 - 失败!", e);

            return;
        }

        /**
         * 第七步、解析结果;具体到此处是解析查询到的结果集。
         */
        if (null != resultSet) {
            try {
                while (resultSet.next()) {
                    int id = resultSet.getInt(1);
                    String provinceName = resultSet.getString("provinceName");
                    String cityName = resultSet.getString("cityName");
                    String districtName = resultSet.getString("districtName");
                    String detail = resultSet.getString("detail");

                    log.info("ID = {}, \t行省:{}, \t地市:{}, \t区县:{}, \t详细:{}"
                            , id, provinceName, cityName, districtName, detail);
                }
            } catch (Exception e) {
                log.error("迭代结果集出错了!", e);
            }
        }

        /**
         * 第八步、关闭 SQL 的【预备声明】对象。
         */
        try {
            preparedStatement.close();
        } catch (SQLException e) {
            log.error("关闭 SQL【预备声明】对象 - 失败!", e);

            return;
        }

        /**
         * 第九步、断开与数据库的连接。
         */
        try {
            connection.close();
        } catch (SQLException e) {
            log.error("关闭 Java 程序与数据库服务端程序的连接 - 失败!", e);
        }
    }

}

  

三、JDBC 10 步实现更新数据的操作:

 

@Test
    public void update_single () {
        /**
         * 第一步、获取数据库的配置
         */
        InputStream databaseConfigInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties") ; // 从【类路径】中获取配置文件
        Properties databaseConfigProperties = new Properties();
        try {
            databaseConfigProperties.load(databaseConfigInputStream);   // 加载【数据库】配置文件
        } catch (IOException e) {
            log.error("加载【数据库配置文件】失败!", e);

            return;
        }

        String username = databaseConfigProperties.getProperty("username");
        String password = databaseConfigProperties.getProperty("password");
        String jdbcURL = databaseConfigProperties.getProperty("jdbcURL");
        String jdbcDriver = databaseConfigProperties.getProperty("jdbcDriver");

        /**
         * 第二步、注册驱动
         */
        try {
            Class.forName(jdbcDriver);
        } catch (ClassNotFoundException e) {
            log.error("没有找到数据库的驱动!", e);

            return ;
        }

        /**
         * 第三步、获取数据库的连接
         */
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(jdbcURL, username, password);
        } catch (SQLException e) {
            log.error("获取 Java 程序与数据库服务端程序的连接对象 - 失败!", e);

            return ;
        }

        /**
         * 第四步、编写(与业务密切相关的)SQL,具体到这里是插入数据的 SQL。
         */
        String insertSQL = "INSERT INTO `t_type` (`parent_id`, `code`, `name`, `remark`, `last_modify_time`)"
                + " VALUES (?, ?, ?, ?, NOW(6) );";

        /**
         * 第五步、创建 SQL 的【预声明】对象,用于对 SQL 语句做准备工作。
         */
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(insertSQL);
        } catch (SQLException e) {
            log.error("创建 SQL【预备声明】对象 - 失败!", e);

            return;
        }

        /**
         * 第六步:为参数值填充参数据。
         */
        int updatedCount = 0;
        try {
            /**
             * 为占位符指定参数值
             * 这是安全的方式,能够有效避免恶意的 SQL 注入,保障系统安全。
             */
            preparedStatement.setInt(1, RandomUtils.nextInt());
            preparedStatement.setString(2, RandomHandle.randomStringGenerator(6));   //
            preparedStatement.setString(3, "名字——" + RandomHandle.randomStringGenerator(2));
            preparedStatement.setString(4, "备注——" + RandomUtils.nextDouble());
        } catch (SQLException e) {
            log.error("为参数值填充数据 - 失败!", e);

            return;
        }

        /**
         * 第七步、执行 SQL 更新操作并获取受影响的行数,具体到此处为执行向数据表中添加数据操作并获取添加成功的行数。
         */
        try {
            updatedCount = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            log.error("执行 SQL 更新(具体到这里是向数据表中添加数据) - 失败!", e);

            return;
        }

        /**
         * 第八步:解析结果,具体到这里为显示插入成功的记录数
         */
        if (0 < updatedCount)
            log.info("成功插入 {} 条数据。", updatedCount);

        /**
         * 第九步、关闭 SQL 的【预备声明】对象。
         */
        try {
            preparedStatement.close();
        } catch (SQLException e) {
            log.error("关闭 SQL【预备声明】对象 - 失败!", e);

            return;
        }

        /**
         * 第十步、断开与数据库的连接。
         */
        try {
            connection.close();
        } catch (SQLException e) {
            log.error("关闭 Java 程序与数据库服务端程序的连接 - 失败!", e);
        }
    }

 

  

 

 

四、注意事项:

  1、JDBC 中的【查询(query)】操作就是大家常说的【读(read)】操作,只包含搜索(search)这一项。

  2、JDBC 中的【更新(update)】操作就是大家常说的【写(write)】操作,包含【添加(insert)】、【更新(update)】、【删除(delete)】。

 

posted @ 2023-04-17 15:45  hapday  阅读(25)  评论(0编辑  收藏  举报