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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:49:08  来源:igfitidea点击:

Reading a datetime value from a SQL database

c#sqldatetime

提问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. 您应该首先检查该值是否DBNullDataReader.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.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...
}