【发布时间】:2017-03-02 10:38:38
【问题描述】:
使用下面的代码:
package com.anonymised.anonymised.anonymised;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class EntryPoint
{
private static Logger logger = LogManager.getLogger(EntryPoint.class);
private static final String JDBC_DRIVER_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static void main(String[] args)
{
logger.info("Service started!");
try
{
Class.forName(JDBC_DRIVER_NAME);
}
catch ( ClassNotFoundException e )
{
logger.error("The necessary JDBC driver is not available (missing dependency?)",e);
System.exit(CrashCodes.JDBC_DRIVER_UNAVAILABLE);
}
// Credentials for connection to the DB
String dbURL = "anonymised:1433";
String dbDatabaseName = "anonymised";
String dbUsername = "anonymised";
String dbPassword = "anonymised";
String connectionUrl = "jdbc:sqlserver://"+dbURL+";" + "databaseName="+dbDatabaseName+";user="+dbUsername+";password="+dbPassword+";";
try
{
Connection con = DriverManager.getConnection(connectionUrl);
}
catch (SQLException e)
{
logger.error("Cannot connect to the database",e);
System.exit(CrashCodes.DATABASE_INITIAL_CONNECTION_FAILED);
}
}
}
我得到以下输出:
[main] ERROR de.anonymised.anonymised.anonymised.EntryPoint - Cannot connect to the database
com.microsoft.sqlserver.jdbc.SQLServerException: SQL Server did not return a response. The connection has been closed.
用户名、密码等都正确,服务器可以访问(我通过数据库管理工具成功创建连接验证了这一点)。
为什么我会得到这个异常?
【问题讨论】:
-
当您使用“数据库管理工具”连接时,
SELECT local_tcp_port FROM sys.dm_exec_connections WHERE session_id=@@SPID是否返回 1433? -
不,它返回 [Null]。
-
因此该连接无法确认 SQL Server 是否可以通过 TCP/IP 访问(它必须使用共享内存或命名管道连接)。 SQL Server 实例可能未在端口 1433 上侦听;您应该验证 TCP/IP 是否已启用并确认它正在使用的端口号。
标签: java sql-server jdbc connection