JDBCUtils工具类,配置文件版

在src下新建dbconfig.properties,输入内容如下

driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc\:mysql\://localhost\:3306/house
user=root
password=g
package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class JDBCUtils{
    private static String user;
    private static String password;
    private static String driverName;
    private static String url;
    static {
        ResourceBundle prop=ResourceBundle.getBundle("dbconfig");
        driverName=prop.getString("driverClass").trim();
        url=prop.getString("jdbcUrl").trim();
        user=prop.getString("user").trim();
        password=prop.getString("password").trim();
    }
    private JDBCUtils(){}

    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(url, user, password);
        }
        catch (ClassNotFoundException e) {
            throw new RuntimeException("请检查驱动是否丢失或配置错误!");
        }catch (SQLException se) {
            throw new RuntimeException("请检查数据库是否连接!");
        }
        return conn;
    }
    public static void close(Connection conn,Statement st,ResultSet rs)
    {
        if(rs!=null)
        {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                rs=null;
            }
        }
        if(st!=null)
        {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                st=null;
            }
        }
        if(conn!=null)
        {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                conn=null;
            }
        }
    }
}

你可能感兴趣的:(JDBCUtils工具类,配置文件版)