我在 Eclipse Neon 中打开了两个使用 JDBC 和 MySQL 的应用程序。
一个应用程序有:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase","root","password");
另一个应用程序有:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase","root","password");
这两个应用我在eclipse中先后运行了好几次。第一个应用程序可以运行以连接并读取和写入数据库。
第二个应用程序总是在调用 DriverManager.getConnection()
方法时给出异常
java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
我用谷歌搜索了这个错误,https://stackoverflow.com/a/12574926/9119247好像说这是我的网络适配器问题。但如果是,为什么它适用于一个应用程序而不适用于另一个应用程序,但我以任何顺序运行它们?
最佳答案
我认为您的第二个应用程序正在连接到 Oracle 数据库和 MySQL 数据库,失败的是与 Oracle 的连接,而不是与 MySQL 的连接。
采用以下(诚然相当愚蠢的)代码:
import java.sql.*;
public class ConnectionsTest {
public static void main(String[] args) throws Exception {
System.out.println("Connecting to MySQL...");
try {
Connection mySQLConnection = DriverManager.getConnection(
"jdbc:mysql://8.8.8.8/3306/mysql", "X", "X");
System.out.println("Odd, got MySQL connection!"); // Shouldn't get here
}
catch (SQLException e) {
System.out.println("MySQL connection failed: " + e.getMessage());
}
System.out.println();
System.out.println("Connecting to Oracle...");
try {
Connection oracleConnection = DriverManager.getConnection(
"jdbc:oracle:thin:@8.8.8.8:1521:ORCL", "X", "X");
System.out.println("Odd, got Oracle connection!"); // Shouldn't get here
}
catch (SQLException e) {
System.out.println("Oracle connection failed: " + e.getMessage());
}
}
}
此代码尝试建立两个数据库连接,一个连接到 Oracle,一个连接到 MySQL,两者都应该失败。 (服务器 8.8.8.8
不会运行任何一个数据库。)当我运行这段代码时,我得到以下输出:
Connecting to MySQL...
MySQL connection failed: 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.
Connecting to Oracle...
Oracle connection failed: IO Error: The Network Adapter could not establish the connection
请注意,MySQL 连接失败错误与您收到的错误不同,而 Oracle 则匹配。
关于java - 两个应用程序使用 JDBC 连接到 mysql 数据库 : one works,,另一个给出 "The Network Adapter could not establish the connection",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47932289/