1. 程式人生 > 其它 >jdbc-對其中三步的封裝

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();
        }
    }

}

}