Schemaspy连接SQL Server 2019失败,求助配置TrustServerCertificate=true
错误原因
SQL Server JDBC驱动默认启用SSL加密(encrypt=true),但你的连接未信任服务器证书(trustServerCertificate=false),导致JVM无法验证证书路径,从而连接失败。你之前配置的schemaspy.trustservercertificate=true未生效,大概率是配置优先级或格式问题。
一、正确的信任证书配置方式
1. 命令行直接指定(最直接生效)
启动Schemaspy时,用-connprops参数传递JDBC连接属性,优先级最高:
schemaspy -t mssql -host <你的SQL Server地址> -port 1433 -db <目标数据库名> -u <用户名> -p <密码> -connprops "trustServerCertificate=true;encrypt=true"
2. 通过配置文件(schemaspy.properties)
在配置文件中添加以下任一配置:
- 方式一:直接指定完整JDBC URL(优先级最高)
schemaspy.jdbc.url=jdbc:sqlserver://<host>:1433;databaseName=<db>;trustServerCertificate=true;encrypt=true schemaspy.jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver schemaspy.u=<用户名> schemaspy.p=<密码>
- 方式二:使用连接属性参数
schemaspy.t=mssql schemaspy.host=<host> schemaspy.port=1433 schemaspy.db=<db> schemaspy.u=<用户名> schemaspy.p=<密码> schemaspy.connprops=trustServerCertificate=true;encrypt=true
二、生产环境合规配置(不跳过证书校验)
如果是生产环境,不建议直接信任未知证书,正确做法是将SQL Server的根证书导入JVM信任库:
- 获取SQL Server的SSL证书(可从服务器管理员处获取,或通过浏览器访问SQL Server SSL端口导出)
- 使用
keytool命令导入证书到JVM默认信任库:
keytool -importcert -file <证书文件路径> -alias sqlserver-cert -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit
导入完成后重启Schemaspy,无需设置trustServerCertificate=true即可正常建立加密连接。
三、Schemaspy SQL Server核心配置项列表
以下是针对SQL Server的常用配置项,可在配置文件或命令行中使用:
schemaspy.t=mssql:指定数据库类型为SQL Serverschemaspy.host=<host>:SQL Server服务器IP/域名schemaspy.port=<port>:SQL Server端口(默认1433)schemaspy.db=<database>:要分析的数据库名称schemaspy.u=<username>:数据库登录用户名schemaspy.p=<password>:数据库登录密码schemaspy.jdbc.url=<jdbc-url>:完整JDBC连接URL(优先级最高,覆盖其他配置)schemaspy.jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver:SQL Server JDBC驱动类schemaspy.connprops=<key=value;key=value>:JDBC连接属性,支持所有SQL Server JDBC驱动参数,常见包括:encrypt=true/false:是否启用SSL加密trustServerCertificate=true/false:是否信任服务器证书(跳过校验)loginTimeout=<数值>:连接超时时间(单位:秒)applicationName=<名称>:设置连接的应用标识integratedSecurity=true/false:是否使用Windows集成身份验证(需额外添加驱动依赖)
原始错误详情
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: "encrypt" property is set to "true" and "trustServerCertificate" property is set to "false" but the driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption: Error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. ClientConnectionId:50cb97cb-80f9-4bb2-a455-71ddb94fa5b6
内容的提问来源于stack exchange,提问作者STWork

