背景:我们开发的之前是用的MySQL,现在需要转到SQL Server 2012数据库上来。但是我从网上也找了很多资料,很多都是很老的,这里搜集了将近两天时间终于调通了,于是记录下来。需要的同学可以进来查看踩坑记录。
环境:
JDK21
SpringBoot 3.3.0
MyBatis-Plus 3.5.6
SQL Server 2012
代码适配
properties配置
spring.datasource.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=test;encrypt=false;trustServerCertificate=true;
spring.datasource.username=sa
spring.datasource.password=123456
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
pom.xml
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.3.jre17</version>
</dependency>
MybatisPlusConfig
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.SQL_SERVER));
return interceptor;
}
MySQL和SQLServer的差异点
tinyint问题
tinyint 只能存储从0 到255之间的整数,不能用来存储负数
MySQL 是 -128 到127之间的数。
limit 1问题
这里SQL Server不支持limit,需要改成top
top 1 就是限制一条,也可以top 3 就是3条数据。
select top 1 * from [table_name]
分页问题
这里推荐使用MyBatis Plus,使用默认的分页插件即可。
报错处理
错误1
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: 通过端口 1433 连接到主机 127.0.0.1 的 TCP/IP 连接失败。错误:“Connection refused: no further information。请验证连接属性。确保 SQL Server 的实例正在主机上运行,且在此端口接受 TCP/IP 连接,还要确保防火墙没有阻止到此端口的 TCP 连接。”。
下面的都改成启动
这里需要拉倒最后,TCP端口改成1433
重启服务,如果不知道怎么重启,直接重启电脑就行。
右击重启启动即可。
错误2
“Encrypt”属性设置为“true”且 “trustServerCertificate”属性设置为“false”,但驱动程序无法使用安全套接字层 (SSL) 加密与 SQL Server 建立安全连接:错误:The server selected protocol version TLS10 is not accepted by client preferences [TLS13, TLS12]。 ClientConnectionId:d254fd06-9dff-4565-9dc3-87f69e14cc60
这里网上好多都说是修改D:\Program Files\Java\jdk-21\conf\security\java.security下面红框的进行删除,但是删了还是会有PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
错误信息。
这里需要改成如下配置:
spring.datasource.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=test;encrypt=false;trustServerCertificate=true;
这里是因为SQL Server2012连接协议比较老了,默认是TLSv1,最新的连接需要TLS1.2及以上。那怎么办呢?
这里需要安装SQL Server2012 SP4,如果你安装的是SP2,这里下载就是更新了,下载安装地址:https://blog.csdn.net/WeiHao0240/article/details/141002703
如何查看当前版本?
select @@VERSION
必须是Microsoft SQL Server 2012 (SP4)
“Encrypt”属性设置为“true”且 “trustServerCertificate”属性设置为“false”,但驱动程序无法使用安全套接字层 (SSL) 加密与 SQL Server 建立安全连接:错误:No appropriate protocol (protocol is disabled or cipher suites are inappropriate)。 ClientConnectionId:782bb4fb-4c8b-49ab-a170-90d57dcb48f9
这个错误也是同上面的配置。
驱动矩阵
可以看到,官网发布的SQL Server 2012连接驱动是10.2,但是我用了最新的也可以,奇了怪了。
参考连接
SQL server 2012 SP4设置TLS1.2
SQL server 中的dbo、guest
Microsoft JDBC Driver for SQL Server support matrix
SQL Server实现Limit语句