优化JDBC工具类,使用配置文件改进

将四个变量的值保存在配置文件中

配置文件要放在src目录下

public class JDBCUtil {
    //成员变量私有
    //定义数据库的连接地址
    private static String url;
    //定义用户名
    private static String userName;
    //定义密码
    private static String passWord;
    //定义驱动类名
    private static String driverClassName;
    //构造方法私有
    private JDBCUtil(){}

    //注册驱动只需要一次,放在静态代码块
    static {
        try {
            //读取配置文件,给成员变量赋值
            Properties prop = new Properties();

            //使用类加载器加载资源要求:配置文件必须放在src根目录下
            InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("config.properties");
//            prop.load(new FileInputStream("src//config.properties"));
            prop.load(in);
            //获取属性值
            url = prop.getProperty("url");
            userName = prop.getProperty("userName");
            passWord = prop.getProperty("passWord");
            driverClassName = prop.getProperty("driverClassName");
            Class.forName(driverClassName);

        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }

    //提供对外获得连接的方法
    public static Connection getConnect() throws SQLException {
        Connection con = DriverManager.getConnection(url, userName, passWord);
        return con;
    }

    //添加一个释放资源的方法
    public static void release(Connection con, Statement stmt, ResultSet rs){
        if (con != null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

当数据库发生改变时,只需要修改配置文件中的内容就可以了。

posted @ 2020-07-26 02:20  硬盘红了  阅读(153)  评论(0编辑  收藏  举报