从SQL数据库中读取日期时间值

时间:2012-10-31 13:55:01

标签: c# sql datetime

如何从SQL数据库中读取日期时间字段?

这不起作用:

emp.DateFacturation = (DateTime)(dr["DateFacturation"])

也不是这样:

emp.DateFacturation = DateTime.Parse(dr["DateFacturation"].toString());

2 个答案:

答案 0 :(得分:6)

由于您已使用以下内容评论了已删除的答案:

  

dr是一个DataReader

您可以使用SqlDataReader.GetDateTime。您应首先检查DBNull的{​​{1}}值是否为DataReader.IsDBNull

DateTime dateFacturation;
int colIndex = dr.GetOrdinal("DateFacturation");
if(!dr.IsDBNull( colIndex ))
    dateFacturation = dr.GetDateTime( colIndex );

我使用GetOrdinal获取列名的列索引,将其传递给GetDateTime

答案 1 :(得分:0)

使用DateTime.TryParse

DateTime datevalue;
if (DateTime.TryParse(dr["DateFacturation"].ToString(), out datevalue))
{
    emp.DateFacturation = datevalue;              
}
else
{
    // TODO: conversion failed... not a valid DateTime
    // Print it out and see what is wrong with it...
}
相关问题