java - 两个应用程序使用 JDBC 连接到 mysql 数据库 : one works,,另一个给出 "The Network Adapter could not establish the connection"

标签 java mysql jdbc

我在 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/

相关文章:

java - java中小数四舍五入并比较小数点后最多3位

mysql - 使用bash脚本重命名mysql中的表

tomcat - 使用tomcat jdbc pool StatementCache拦截器时出错

jdbc - 当连接返回到池时,BoneCP(或任何其他池)是否关闭连接的语句?

java - 最佳图像缩放库

java - "Tomcat 7 JDBC Connection Pool"是否足以用于生产?它与 BoneCP 相比如何?

Python 在我的查询参数中添加单引号

尝试在 MySQL 中连接时出现 java.net.ConnectException

java - 如何访问 Web api 方法内的资源过滤器中生成的对象

mysql - 如何提高 C# 中 MySQL 存储过程调用的速度