收到以下错误:com.microsoft.sqlserver.jdbc.SQLServerException:驱动程序无法使用安全套接字层 (SSL) 加密与 SQL Server 建立安全连接。错误:“连接被对等方重置:套接字写入错误。”
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionString =
"jdbc:sqlserver://XXXXX.database.windows.net:1433;"
+ "database=VDB;"
+ "user=XXX@VVV;"
+ "password=XXXX;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "hostNameInCertificate=*.database.windows.net;"
+ "loginTimeout=30;";
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 2 * from Application";
statement = connection.createStatement();
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(2) + " "
+ resultSet.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the connections after the data has been handled.
if (resultSet != null) try {
resultSet.close();
} catch (Exception e) {
}
if (statement != null) try {
statement.close();
} catch (Exception e) {
}
if (connection != null) try {
connection.close();
} catch (Exception e) {
}
}
}
}
我只是尝试执行 Azure 站点上引用的“示例”连接代码片段(指向 MS 条目),仅进行修改以匹配我的数据库和测试表,但没有成功。
回顾了所有需要知道的内容后,我:-
- 确保我使用正确的 sqljdbc(我已尝试了所有 4 个)
- 在 CLASSPATH 中包含 sqlauth.dll
- 已完全按照所示方式设置示例;并合并了 Azure 提供的字符串。
我尝试了加密和信任的各种组合,但没有成功。由于我是 Java 和 Azure 的新手,我不愿意并且不确定如何修改 JVM 安全设置。
我已经证明我的机器可以与 Azure 数据库通信(通过 VB ODBC 连接);我已经在防火墙关闭的情况下进行了测试。
有什么想法吗?
最佳答案
我尝试重现该问题,但未能使用与您的代码类似的代码访问我的 SQL Azure 实例。
除了使用我的sql azure实例的连接字符串之外,我们的代码之间的区别仅如下所示。
- 使用
sqljdbc_4.0
中的驱动程序sqljdbc4.jar
link . - 使用代码
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
加载 MS SQL JDBC 驱动程序。 - 未将
sqlauth.dll
文件添加到CLASSPATH
中。 - 检查我的客户端 IP 是否已被 SQL Azure IP 防火墙允许。
- 使用sql
select 1+1
测试我的代码,并从代码result.getInt(1)
中获取值4
。
这对我来说很好。如果您能为我们提供更多的细节,我认为这对分析问题很有帮助。
希望有帮助。
关于java - 由于 SSL 问题,无法使用 JDBC 连接到 Azure(基于连接字符串和提供的示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40877875/