sql 加密代码 java_Java代码SSL https 加密连接 sqlserver
时间: 2023-10-12 10:04:44 浏览: 62
以下是Java代码示例,演示如何使用SSL加密连接SQL Server数据库:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLServerSSLTest {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
String url = "jdbc:sqlserver://localhost:1433;databaseName=mydb;encrypt=true;trustServerCertificate=true;";
String user = "sa";
String password = "password";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(url, user, password);
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
System.out.println(rs.getString("column1"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,我们使用JDBC驱动程序连接到SQL Server数据库。在连接字符串中,我们传递了`encrypt=true`和`trustServerCertificate=true`参数,这将使用SSL加密连接,并信任服务器证书。
请注意,在使用SSL加密连接时,您需要在SQL Server上配置证书。如果您还没有配置证书,请参阅Microsoft文档以获取详细说明。