jdbc-对其中三步的封装

package com.cqust.utils;

import java.sql.*;

public class JDBCUtil {
static {
try {
//注册驱动类加载的时候执行
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

private JDBCUtil() {
}
//获取连接
public static Connection getConnection(){
    Connection connection = null;
    try {
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cqust_db","root","hch1");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return connection;

}

//关闭资源
public static void closeAllResources(Connection connection,Statement statement,ResultSet resultSet){


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

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

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

}

}

posted @ 2021-11-19 09:03  journeyhch  阅读(32)  评论(0)    收藏  举报