首页 > 解决方案 > 如何在 Java (JDBC) 中处理静态字段的错误

问题描述

我正在尝试创建一个类,我可以在其中使用适当的 jdbc 驱动程序建立与 MySQL 数据库的连接,打开连接并关闭它。我想在具有静态最终字段的单独类中执行此操作,以便用户、密码、dburl 凭据在代码本身中不可见,而是从文件中获取。但是,当我尝试将值分配给静态字段时,我使用的类方法可能会引发 FileNotFound 和 SQL 异常,我不知道如何在此类中处理它们。我应该怎么做才能让我的 IDE 接受我编写的代码?还是我需要以某种方式重构代码并且有更好的方法来做到这一点?这是我的代码:

public class DBConnection {

        private static Properties properties = new Properties().load(new FileInputStream("DBProperties"));

        private static final String user = properties.getProperty("user");
        private static final String pwd = properties.getProperty("password");
        private static final String dburl = properties.getProperty("dburl");
        private static Connection myConn = DriverManager.getConnection(dburl, user, pwd);


        public void closeConnection() {
                try {
                        if (myConn != null) {
                                myConn.close();
                        }
                } catch (SQLException e) {
                        System.out.println("Couldn't close connection : " + e.getMessage());
                }
        }
}

在此先感谢您的帮助

标签: javaexception-handling

解决方案


尝试将您的代码包装到一个静态块中:

static {

// your code 

}

推荐阅读