封装JDBC工具类

封装JDBC工具类

  • 在实际JDBC的使用中,存在着大量的重复代码:例如连接数据库、关闭数据库等这些操作!
  • 我们需要把传统的JDBC代码进行重构,抽取出通用的JDBC工具类!以后连接的任何数据库、释放资源都可以使用这个工具类

工具类核心思想

重用性方案

  • 封装获取连接、释放资源两个方法
    • 提供public static Connection getConnection()方法。
    • 提供public static void closeAll(Connection connection,Statement statement,ResultSet resultSet)方法。

跨平台方案

  • 定义public static final Properties properties=``new Properties();//读取配置文件的Map

跨平台实现

src目录下新建db.db.properties文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc
username=root
password=root

工具类代码:

package com.qf.jdbc2;

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

public class DBUtils {
    private static final Properties PROPERTIES = new Properties();//存储配置文件的Map

    static {
        try {
            //选择读取文件的路径
            InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
            PROPERTIES.load(is);
            Class.forName(PROPERTIES.getProperty("driver"));
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //连接数据库
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(PROPERTIES.getProperty("url"),
                    PROPERTIES.getProperty("username"),
                    PROPERTIES.getProperty("password"));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //释放资源
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
posted @ 2020-09-08 00:57  Techoc  阅读(154)  评论(0编辑  收藏  举报