我有一个 ODBC 数据源,其中一列是 DateTime。如果我尝试对字段 ( IsDbNull
, GetValue
, GetValues
) 执行任何操作,如果值是此数据库等效于 null,我将收到异常。
System.ArgumentOutOfRangeException occurred
HResult=-2146233086
Message=Year, Month, and Day parameters describe an un-representable DateTime.
Source=mscorlib
StackTrace:
at System.DateTime.DateToTicks(Int32 year, Int32 month, Int32 day)
at System.DateTime..ctor(Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second)
at System.Data.ProviderBase.DbBuffer.ReadDateTime(Int32 offset)
at System.Data.Odbc.CNativeBuffer.MarshalToManaged(Int32 offset, SQL_C sqlctype, Int32 cb)
at System.Data.Odbc.OdbcDataReader.internalGetDateTime(Int32 i)
at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i, TypeMap typemap)
at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i)
at System.Data.Odbc.OdbcDataReader.IsDBNull(Int32 i)
at Sandbox_Form.Form1.button1_Click(Object sender, EventArgs e) in e:\Code\Sandbox Form\Form1.cs:line 49
InnerException:
如果我将查询更改为select cast(First_Visit as varchar) as First_Visit_cast from Clients
我得到的文本字符串0/0/0 12:00:00
作为结果返回。
这是我的测试代码片段。前 17 行工作正常,但第 18 行具有“空”值日期并引发显示的异常。
const string Query = @"select cast(First_Visit as varchar) as First_Visit_cast
,First_Visit
from Clients";
private void button1_Click(object sender, EventArgs e)
{
using (var con = new OdbcConnection("Dsn=My_ODBC_DSN"))
{
con.Open();
using (var cmd = new OdbcCommand(Query, con))
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
var test = rdr.GetValue(0); //returns "0/0/0 12:00:00" as string.
var test3 = rdr.IsDBNull(1); //Throws an ArgumentOutOfRangeException: "Year, Month, and Day parameters describe an un-representable DateTime."
var test2 = rdr.GetValue(1); //Throws an ArgumentOutOfRangeException: "Year, Month, and Day parameters describe an un-representable DateTime."
var records = new object[rdr.FieldCount];
rdr.GetValues(records); //Throws an ArgumentOutOfRangeException: "Year, Month, and Day parameters describe an un-representable DateTime."
}
}
}
}
有没有办法解决这个问题?我真的想只写我的查询,Select * from TableName
而不是识别所有的 DateTimes 并将它们显式转换为字符串。