我正在开发一个 Java 应用程序,该应用程序可以连接到我的办公室网络,也可以不连接到我的办公室网络。
我的问题是,当用户未连接时,DriverManager.getConnection()
需要长达 20 秒的时间才能最终发布无法连接到数据库的消息。
将我连接或不连接到服务器的代码:
public static Connection getConnection() {
try{
//cnx is my Connection object
if(cnx ==null || cnx.isClosed()){
Class.forName("com.mysql.jdbc.Driver");
//Get the connection if possible
cnx = DriverManager.getConnection(connectionString, user, password);
}
/*
Basically, I'm just checking if "ConfigUser.isConnected()" is true
later in the code to know if I should try to execute SQL queries
*/
ConfigUser.setConnected(true);
return cnx;
}
catch (Exception e){
}
ConfigUser.setConnected(false);
return null;
}
我尝试使用 DriverManager.setLoginTimeout()
函数,但它似乎没有改变任何内容。
最佳答案
添加到connectionString
connect timeout in milliseconds :
&connectTimeout=5000
connectTimeout
Timeout for socket connect (in milliseconds), with 0 being no timeout. Only works on JDK-1.4 or newer. Defaults to '0'.
关于java - JDBC DriverManager 在尝试连接数据库之前检测用户是否在网络上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53152692/