【发布时间】:2019-03-25 13:36:39
【问题描述】:
我正在执行一个简单的 SELECT 语句,并尝试从 SQL Server 2012 表的 DateTime 列中返回值。问题是,当我返回 NULL DateTime 值时,我不知道如何使用下面的代码来管理它。
dtTrainingEnd = (DateTime)reader["TrainingEnd"];
过去几天我一直在寻找答案,但找不到对我有帮助的东西。我发现了类似的帖子,但我仍然无法弄清楚它们如何帮助我。您能解释一下我如何检查从数据库返回的日期时间值是否为 NULL 吗?
SqlConnection connRead = new SqlConnection(connReadString);
SqlCommand comm = new SqlCommand();
SqlDataReader reader;
string sql;
DateTime dtTrainingEnd = DateTime.Now;
int iTrainingSwipeID = 123;
sql = "SELECT TrainingEnd FROM TrainingSwipe WHERE TrainingSwipeID = " + iTrainingSwipeID;
comm.CommandText = sql;
comm.CommandType = CommandType.Text;
comm.Connection = connRead;
connRead.Open();
reader = comm.ExecuteReader();
while (reader.Read())
{
dtTrainingEnd = (DateTime)reader["TrainingEnd"];
}
connRead.Close();
【问题讨论】:
-
关于 DateTime 类型的说明,DateTime 是一种(结构)值类型,当检索空值时,它会将自身设置为默认值。此类型的默认值为 '01/01/0001'。
-
如果数据库允许空值,你的代码也应该这样做。考虑在涉及这些列的情况下使用可为空的类型。
标签: c# sql-server datetime casting