java - 如何在 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());
}
}
}
在此先感谢您的帮助
解决方案
尝试将您的代码包装到一个静态块中:
static {
// your code
}
推荐阅读
- java - 在片段内使用回收器视图时出错
- mongodb-query - 有没有办法执行单个 mongo 查询来比较 ID 数组?
- node.js - Elastic Beanstalk 预部署 Laravel 节点错误
- rust - 如何重用加载在紫水晶中的资产?
- r - 如何列出在函数中调用的所有用户定义函数或 R 中的用户定义函数?
- expo - React Native 中 Expo 的 PayloadTooLargeError
- java - 将 gitlab JDK 更新为 JDK17(VM 没有互联网连接)
- python - 带有切片字符串的 Python 迭代器
- javascript - 为什么 setState 不更新我的状态值?
- google-cloud-platform - 将事务消息路由到无服务器实例