jdbc之工具类DBUtil的使用

  首先回顾一下jdbc的使用方法:

  1. 注册驱动

  2. 建立连接

  3. 建立statement

  4. 定义sql语句

  5. 执行sql语句,如果执行的是查询需遍历结果集

  6. 关闭连接

  其中建立连接和关闭连接都是可以封装成工具类的,因此给出DBUtil代码如下:

package com.colin.util;

import java.sql.*;

public class DBUtil {

    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/testdb";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "Danny2036";

    /**
     * 获取连接的公共方法
     * @return
     */
    public static Connection getConnection() {

        try {
            Class.forName(DRIVER);
            return DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 关闭Connection
     * @param connection
     */
    public static void closeConnection(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭Statement
     * @param statement
     */
    public static void closeStatement(Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭ResultSet
     * @param resultSet
     */
    public static void closeresultset(ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭ResultSet, Statement, Connection
     * @param closeables
     */
    public static void closeAll(AutoCloseable... closeables) {
        for(AutoCloseable autoCloseable : closeables) {
            try {
                if (autoCloseable != null) {
                    autoCloseable.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

  这里解释下最后一个方法closeAll()。关闭连接需要关闭哪些内容呢?一般情况下,有Connection和Statement,如果执行查询返回了结果集,还有ResultSet。关闭的顺序应该和打开的顺序相反(如,打开的顺序是Connection,Statement,关闭的顺序就应该是Statement,Connection)。如果分别写三个close方法,很明显代码不够精炼。因此,我们只用一个方法来关闭所有的连接。

  通过查看源码可以知道,Connection,Statement,ResultSet都继承了AutoCloseable这个接口,因此closeAll()方法采用AutoCloseable类型的可变参数,传入的三个值按顺序依次是ResultSet(如果有),Statement,Connection。给出如下一个例子。

DBUtil.closeAll(resultSet, preparedStatement, connection);

  大功告成。

猜你喜欢

转载自www.cnblogs.com/AlleyMeowy/p/10205124.html