有人可以解释一下为什么下面的程序在 3 秒后超时,因为我将其设置为在 3 秒后超时
12秒。我特意关闭了mysql服务器来测试mysql服务器无法访问的这种场景。
import java.sql.Connection;
import java.sql.DriverManager;
/**
*
* @author dhd
*/
public class TestMysql {
static Thread trd;
public static void main(String[] argv) {
keepTrack();
try {
DriverManager.setLoginTimeout(12);
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/driving", "root", "");
} catch (Exception ex) {
System.err.println(ex.getMessage());
trd.stop();
}
}
public static void keepTrack() {
trd = new Thread(new Runnable() {
@Override
public void run() {
int i = 1;
while (true) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (Exception ex) {
}
i++;
}
}
});
trd.start();
}
}
输出是:
run:
1
2
3
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
BUILD SUCCESSFUL (total time: 3 seconds).
从 netbean 运行。在询问为什么我需要这个之前,请先回答。谢谢
如果MySQL服务器没有运行,连接不会超时;操作系统立即回复“连接被拒绝”错误。要使连接超时,您可以做的一件事是配置防火墙以丢弃到达 MySQL 端口的所有数据包。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)