C# 从 SQL 数据库读取日期时间值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13159617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a datetime value from a SQL database
提问by Med Amine
How can I read datetime fields from a SQL database?
如何从 SQL 数据库中读取日期时间字段?
This is not working:
这不起作用:
emp.DateFacturation = (DateTime)(dr["DateFacturation"])
nor is this:
这也不是:
emp.DateFacturation = DateTime.Parse(dr["DateFacturation"].toString());
回答by Tim Schmelter
Since you've commented a now deleted answer with:
由于您评论了现已删除的答案:
dr is a DataReader
dr 是一个 DataReader
You can use SqlDataReader.GetDateTime. You should check first if the value is DBNullwith DataReader.IsDBNull:
您可以使用SqlDataReader.GetDateTime. 您应该首先检查该值是否DBNull为DataReader.IsDBNull:
DateTime dateFacturation;
int colIndex = dr.GetOrdinal("DateFacturation");
if(!dr.IsDBNull( colIndex ))
dateFacturation = dr.GetDateTime( colIndex );
I use GetOrdinalto get the column index of the column name to pass it to GetDateTime.
我GetOrdinal用来获取列名的列索引以将其传递给GetDateTime.
回答by Carlos Quintanilla
Use 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...
}

