人事管理系统 连接 关闭 方法

2018-01-24  本文已影响0人  吴鹏608
package com.company;

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

/**
 * Created by ttc on 18-1-22.
 */
public class JDBCUtils {
    private static Connection conn = null;

    static {
        InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");

        //新建一个Property对象
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //1.加载mysql数据库驱动
        try {
            Class.forName(properties.getProperty("driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //2.获得数据库连接对象
        String url = properties.getProperty("url");//要连接的数据库服务器的基本信息,包括(ip,端口,数据库名)
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");

        try {
            conn = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private JDBCUtils(){}




    public static Connection getConnection()
    {
        return conn;
    }

    public static void close(Statement statement, Connection connection)
    {
        if(statement != null)
        {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

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

    }

    public static void close(ResultSet resultSet, Statement statement, Connection connection)
    {
        if(resultSet != null)
        {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

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

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

    }
}


上一篇下一篇

猜你喜欢

热点阅读