我的应用程序使用了一个 Mysql 连接,它是使用以下代码获得的:
public static void Connect(){
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://" + host + ":" + port + "/"+ db;
ct = DriverManager.getConnection(url, user, pass);
st = ct.createStatement();
System.out.println("Csatlakozva....\n");
}
catch (InstantiationException e)
{
Main.textArea.setText("Error : Instantiation!");
//System.err.println("Error : Instantiation");
e.printStackTrace();
}
catch (IllegalAccessException e)
{
Main.textArea.setText("Error : Illegális Behatolás!");
//System.err.println("Error : Illegális Behatolás!");
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
Main.textArea.setText("Error : Class Nem Található!");
//System.err.println("Error : Class Nem Található!");
e.printStackTrace();
}
catch (SQLException e)
{
Main.textArea.setText("Error : Adatbázis Nem Található!");
//System.err.println("Error : Adatbázis Nem Található!");
e.printStackTrace();
}
}
如果 MySQL 数据库服务器未运行,因此我的应用无法打开连接,我该如何让我的应用等待连接建立?
最佳答案
为了让您的 Connect
方法在实际获得连接之前不返回,您需要用循环包围现有的 try-block。像这样:
public static void Connect() throws InterruptedException { // It isn't nice to block forever, so we will allow for interrupt
for (;;) {
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://" + host + ":" + port + "/"+ db;
ct = DriverManager.getConnection(url, user, pass);
st = ct.createStatement();
System.out.println("Csatlakozva....\n");
return; // Break out of loop because we got a connection - no exception was thrown
} ...
// One of the exceptions happened. We will continue to loop so
// we try to connect again until we are successful. We don't want
// to retry too fast, because painful experience has taught us that
// bad things can happen (full logs, 100% CPU, etc.).
Thread.sleep(1);
}
}
探索和理解这些低级问题是一个很好的练习。但是,我在这里只做一个说明,(根据我的经验)大多数应用程序使用连接池来管理数据库连接。一般来说,连接池会提供阻塞(通常是有限的时间)直到获得连接的功能。换句话说,连接池不仅允许重用以前创建的连接,还可以在必要时处理连接重试。
关于Java等待Mysql连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37953850/