jdbc.util

package com.hisoft.epetshop.util;

import java.sql.*;

/**
 * @program: epetShop-01
 * @description:
 * @author: wlg
 * @create: 2020-10-13 11:10:54
 **/
public class JdbcUtil {

    private static String URL = "jdbc:mysql:///epetshop";
    private static String DRIVER = "com.mysql.jdbc.Driver";
    private static String USER = "root";
    private static String PASSWORD = "root";

    static {
        //1.加载驱动
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     */
    public static Connection getConnection(){
        //2.获取连接
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
            System.out.println("连接成功");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 释放资源
     * @param connection
     * @param stmt
     * @param rs
     */
    public static void closeAll(Connection connection, Statement stmt, ResultSet rs){
        //6.释放资源--Connection,Statement,ResultSet
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

posted @ 2020-10-13 16:31  Coast-  阅读(29)  评论(0)    收藏  举报