【问题标题】:Unable to link Java program to SQL database无法将 Java 程序链接到 SQL 数据库
【发布时间】:2013-12-14 23:49:35
【问题描述】:

我一直在尝试在我的 Java 程序中实现与任何数据库管理系统的基于 JDBC 的数据库连接。首先我尝试使用 Microsoft SQL Server Management Studio,我的代码如下所示:

public class ConnectionCreate {
    public connectionCreate(){
        try {
            //SQL Server Manager Settings
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=test","test","test" );
            System.out.println("Connection Established");

        }catch(Exception e){
            System.out.println(e);
        }
    }
}

我的测试数据库名为 test,托管在 SQL Server Management Studio 的 1433 端口上,并表示它正在运行。我可以通过 Studio GUI 修改它,添加表格等,但每当我调用我的 Java 代码时,它都会失败:

  Exception: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Invalid argument: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.

我已经检查了我能想到的所有内容,因为 Class.forName 调用没有问题,所以肯定会为 JDBC 库找到 jar 文件。我一直在使用 SQL Server 网络配置 > 协议,并确保所有连接类型都已启用,包括 TCP/IP。我已经确定要使用的默认端口是 1433。我什至完全禁用了我的防火墙以防万一,但它仍然拒绝工作。

出于绝望,我还尝试了不同的数据库管理工具。 XAMPP 使用 PhpmyAdmin 和 mysql。我再次正确附加了必要的 .jar,确保它在我的网络浏览器中本地运行良好,并在我的 Java 测试脚本中使用了以下代码:

public class ConnectionCreate {
    public connectionCreate(){
        try {
            //MySQL Settings
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            System.out.println("Connection Established");

        }catch(Exception e){
            System.out.println(e);
        }
    }
}

当我运行我的 Java 测试程序时,这也会给我一个错误。它指出:

 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 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.

我完全不知道该怎么做,我似乎无法在我的 Java 程序中建立任何有效的数据库连接,我不确定我还需要在我的系统上或使用我的代码使它工作。 任何帮助都会很棒!

【问题讨论】:

  • 你能用一个非常简单的程序来复制它吗?只是为了确认这不是程序其他部分的问题?这里有一个非常简单的 JDBC 程序,您可以使用以下代码进行测试:support.microsoft.com/kb/313100

标签: java mysql sql sql-server jdbc


【解决方案1】:

我看到 SQL Server 在同一台机器上。

如果您启用了通过 TCP/IP 访问,我认为您需要检查 SQL Server 配置管理器,因为 SSMS 可以使用本机(非 TCP/IP)协议。

请参阅 TechNet:http://technet.microsoft.com/en-us/library/ms187892(v=sql.105).aspx

【讨论】:

  • 我之前已经按照该教程进行操作,并确保在我的数据库上启用了 TCP/IP,默认监听的帖子为 1433,我的 Java 尝试使用这些设置。但是它仍然不起作用,并且我收到与之前声明“无效参数:连接”相同的错误
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 2015-10-18
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多