C# 日期时间到 ODBC 日期时间转换错误

2024-06-22

我们正在尝试将 ODBC 与 SQL Server 2012 一起用于我们的新应用程序,因为 MS 正在逐步淘汰 OleDb,而我们希望尝试使其更容易(更容易?)移植到其他数据库。

问题是,当我尝试使用 ODBC 数据访问类时,在尝试保存日期时间时出现以下错误:

错误 [22008] [Microsoft][SQL Server Native Client 11.0]日期时间字段 溢出。小数秒精度超出了中指定的范围 参数绑定。

好吧,我明白了。 C# 具有比 ODBC 参数想要使用的更高的精度。我知道 ODBC 实现不喜欢秒的几分之一,但是如何保留日期时间精度呢?

Thanks,

Dinsdale

编辑:好的,这是原始参数构造函数:

String Name = "created";
DateTime DateTimeValue = DateTime.Now;
OdbcCommand cmd = new OdbcCommand();
cmd.CommandType = request.CommandType;
cmd.CommandText = request.Command;
OdbcParameter param;
param = new OdbcParameter(Name, OdbcType.DateTime);
param.Value = DateTimeValue;
cmd.Parameters.Add(param);

此代码生成以下错误: 错误 [22008] [Microsoft][SQL Server Native Client 11.0]日期时间字段溢出。小数秒精度超出了参数绑定中指定的范围。

解决方法是使用扩展构造函数,如下所示:

param = new OdbcParameter(Name, OdbcType.DateTime, 23, System.Data.ParameterDirection.Input, false, 0, 3, Name, DataRowVersion.Current, DateTimeValue);

再次感谢库莫德! 丁斯代尔


小数秒精度超出了参数绑定中指定的范围。

这意味着第二精度大于Scale的财产OdbcParameter目的。 为了DateTime格式:

yyyy-mm-dd hh:mm - Precision = 16, Scale = 0

yyyy-mm-dd hh:mm:ss - Precision = 19, Scale = 0

这是那些需要的Scale要超过的属性(它是0默认情况下)

yyyy-mm-dd hh:mm:ss.f - Precision = 21, Scale = 1

yyyy-mm-dd hh:mm:ss.ff - Precision = 22, Scale = 2

yyyy-mm-dd hh:mm:ss.fff - Precision = 23, Scale = 3

each f是额外的小数秒精度

OdbcParameter param = new OdbcParameter( "name", OdbcType.DateTime );
param.Value = DateTime.Now;
param.Precision = 23;
param.Scale = 3; // <-- you need to set this property
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 日期时间到 ODBC 日期时间转换错误 的相关文章

随机推荐