我正在尝试使用 java 中的 singleton 类连接到我的数据库。这是我当前的代码:
public class Database {
public static Database instance;
private Connection connection;
private Database() {
try {
Class.forName("com.mysql.jdbc.Driver");
Log.debug("ok");
this.connection = DriverManager.getConnection("jdbc:mysql://just.not.for.you:3006/database?connectTimeout=5000", "database", "secret");
Log.debug("ok");
} catch (ClassNotFoundException e) {
Log.warn("Cloud not find jdbc driver class");
} catch (SQLException e) {
Log.warn("Cloud not connect to database: " + e.getMessage(), e);
}
}
public static synchronized Database getInstance() {
if(Database.instance == null) {
Database.instance = new Database();
}
return Database.instance;
}
在我的主类中,我调用 Database.getInstance()
但什么也没发生。没有错误,没有超时消息。这似乎是一个无限循环。我在第 10 行看到第一条调试消息,但没有在第 12 行看到消息。
问题是什么?
编辑:我可以使用本地计算机使用 mysql workbench 连接到远程数据库
最佳答案
我发现你的代码有问题!
- 将
com.mysql.jdbc.Driver
替换为新驱动程序com.mysql.cj.jdbc.Driver
,因为它已被弃用 - 查看mysql服务器端口,默认端口是3306而不是3006
关于Java jdbc 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003650/