JDBC工具类封装

需要完成的内容
	1. 数据库连接对象java.sql.Connection获取过程
	2. 关闭资源

JDBC工具类
	1. 所有的方法都是static修饰的静态方法
	2. 需要考虑自动加载过程,完成一些必要数据的自动处理
		url
		driver
		user
		password
	3. 所需数据库连接条件保存到文件中
	4. 关闭方法提供多种多样组合方法

【注意】
	db.properties文件保存到src目录下
# 当前JDBC连接所需的驱动
driverClass=com.mysql.jdbc.Driver

# 数据库连接符合JDBC规范的url
url=jdbc:mysql://localhost:3306/nzgp2001?useSSL=true

# 用户名
user=root

# 密码
password=123456
package util;

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

/**
 * JDBC工具类,负责数据库连接对象和数据库资源关闭
 *
 * @author Anonymous 2020/3/24 10:08
 */
public class JdbcUtil {
    // 静态成员变量,保存一些必要的数据
    private static String url = null;
    private static String user = null;
    private static String password = null;


    // 利用static修饰的静态代码块完成文件字段自动读取和驱动自动加载过分
    static {
        try {
            // Properties实现类,里面的数据保存形式都是键值对形式
            Properties properties = new Properties();

            // 使用字节输入流,加载对应db.properties,数据保存到Properties对象中
            properties.load(new FileInputStream("./src/db.properties"));

            // 从Properties读取对应的数据
            String driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");

            // 完整驱动加载
            Class.forName(driverClass);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回数据库连接对象,连接失败返回null
     *
     * @return java.sql.Connection 数据库连接对象
     */
    public static Connection getConnection() {
        Connection connection = null;

        try {
            // 通过DriverManager驱动管理类,使用必要参数获取数据库连接
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;
    }

    /*
    以下三个方法实际上都是执行同一个方法,使用这种方式
        1. 简化代码结构
        2. 规范化所有的操作
     */

    /**
     * 处理数据库操作对应的资源问题
     *
     * @param connection java.sql.Connection 数据库连接对象
     */
    public static void close(Connection connection) {
        close(connection, null, null);
    }

    /**
     * 处理数据库操作对应的资源问题
     *
     * @param connection java.sql.Connection 数据库连接对象
     * @param statement java.sql.Statement 数据库SQL语句搬运工对象
     */
    public static void close(Connection connection, Statement statement) {
        close(connection, statement, null);
    }

    /**
     * 处理数据库操作对应的资源问题
     *
     * @param connection java.sql.Connection 数据库连接对象
     * @param statement java.sql.Statement 数据库SQL语句搬运工对象
     * @param resultSet java.sql.ResultSet 数据库查询结果集对象
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

            if (statement != null) {
                statement.close();
            }

            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

2 PreparedStatement使用

2.1 PreparedStatement插入数据SQL完成
@Test
public void testInsert() {
    User user = new User(10, "逗比匿名君", "123456");
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        // 获取数据库连接
        connection = JdbcUtil.getConnection();
        // 准备SQL语句
        // ? 表示SQL语句参数占位符!!!
        String sql = "insert into nzgp2001.user(id, userName, password) VALUE (?,?,?)";
        // 预处理SQL语句,获取PreparedStatement对象
        preparedStatement = connection.prepareStatement(sql);
        // SQL语句赋值操作,SQL语句参数是从1开始
        preparedStatement.setObject(1, user.getId());
        preparedStatement.setObject(2, user.getUserName());
        preparedStatement.setObject(3, user.getPassword());
        // 使用PreparedStatement执行SQL语句
        int affectedRows = preparedStatement.executeUpdate();
        System.out.println("affectedRows:" + affectedRows);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JdbcUtil.close(connection, preparedStatement);
    }
}
2.2 PreparedStatment修改SQL完成
@Test
public void testUpdate() {
    User user = new User(10, "逗比匿名君", "航海中路彭于晏");
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = JdbcUtil.getConnection();
        String sql = "update user set userName = ?, password = ? where id = ?";
        preparedStatement = connection.prepareStatement(sql);
        // 赋值SQL语句参数
        preparedStatement.setObject(1, user.getUserName());
        preparedStatement.setObject(2, user.getPassword());
        preparedStatement.setObject(3, user.getId());
        int affectedRows = preparedStatement.executeUpdate();
        System.out.println("affectedRows:" + affectedRows);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JdbcUtil.close(connection, preparedStatement);
    }
}
##### 3.3 PreparedStatment删除SQL完成
```java
@Test
public void testDelete() {
    int id = 7;
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = JdbcUtil.getConnection();
        String sql = "delete from user where id = ?";
        preparedStatement = connection.prepareStatement(sql);
        // 赋值参数
        preparedStatement.setObject(1, id);
        int affectedRows = preparedStatement.executeUpdate();
        System.out.println("affectedRows:" + affectedRows);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JdbcUtil.close(connection, preparedStatement);
    }
}
2.4 PreparedStatment查询SQL完成
@Test
public void testSelectOne() {
    int id = 10;
    User user = null;
    
    ResultSet resultSet = null;
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    
    try {
        connection = JdbcUtil.getConnection();
        String sql = "select * from user where id = ?";
        preparedStatement = connection.prepareStatement(sql);
        
        // 赋值参数
        preparedStatement.setObject(1, id);
        resultSet = preparedStatement.executeQuery();
        
        if (resultSet.next()) {
            String userName = resultSet.getString("userName");
            String password = resultSet.getString("password");
            user = new User(id, userName, password);
        }
        
        if (user != null) {
            System.out.println(user);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JdbcUtil.close(connection, preparedStatement, resultSet);
    }
}
@Test
public void testSelectAll() {
    List<User> list = new ArrayList<>();
    
    ResultSet resultSet = null;
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    
    try {
        connection = JdbcUtil.getConnection();
        String sql = "select * from user";
        
        preparedStatement = connection.prepareStatement(sql);
        resultSet = preparedStatement.executeQuery();
        
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String userName = resultSet.getString("userName");
            String password = resultSet.getString("password");
            list.add(new User(id, userName, password));
        }
        
        for (User user : list) {
            System.out.println(user);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        JdbcUtil.close(connection, preparedStatement, resultSet);
    }
}
发布了32 篇原创文章 · 获赞 31 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40197991/article/details/105078466
今日推荐