You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止JDBC驱动将SQL Server datetime转为datetime2致更新失败?

解决mssql-jdbc驱动自动将datetime转为datetime2导致更新失败的问题

问题背景

使用Spring Batch框架通过mssql-jdbc驱动操作SQL Server时,以datetime类型的主键col1为条件更新数据,驱动会自动将时间参数转为datetime2类型,导致隐式转换后与表中存储的datetime值精度不匹配,最终更新无生效行。

解决方案

可以通过以下方式强制驱动使用datetime类型发送时间参数:

  1. 在JDBC连接字符串中添加sendTimeAsDatetime=true参数
    mssql-jdbc驱动默认对SQL Server 2008及以上版本,会将Java时间类型转为datetime2传递,该参数可强制驱动改用datetime类型传递时间参数。
    示例连接字符串:
jdbc:sqlserver://your-server-address:1433;databaseName=your-database;sendTimeAsDatetime=true;
  1. Spring Boot环境下配置数据源属性
    在application.properties中配置:
spring.datasource.url=jdbc:sqlserver://your-server-address:1433;databaseName=your-database;sendTimeAsDatetime=true
spring.datasource.username=your-username
spring.datasource.password=your-password
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
  1. 实体类字段明确指定SQL类型
    确保实体类中对应datetime字段的注解明确指定SQL类型为datetime,避免框架自动映射为datetime2:
@Id
@Column(name = "col1", columnDefinition = "datetime", nullable = false)
private Timestamp col1;

验证效果

配置完成后,SQL Server Profiler捕获的更新语句中,参数@P1的类型会变为datetime,参数值将与表中存储的2024-04-28 20:18:43.703精确匹配,从而正常更新目标行。

内容的提问来源于stack exchange,提问作者Aayushi Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:45:14