我正在尝试使用 C# .Net 中的 MySqlDataReader 迭代我的 MySQL 数据库,但我无法首先检查任何 DateTime 列是否为空。我已经制作了一个动态列表(“MyList”)并计划迭代数据库并使用自定义字段添加每个项目,其中一些是 DateTimes,但在此过程中我收到错误消息“无法调用此方法或属性关于 Null 值。”
对于字符串值,我通常使用这种内联语法来检查列是否为空:
Value = reader["Name"] != null ? reader["Name"].ToString() : ""
但是对于 DateTime 列似乎有一个不同的过程,我无法弄清楚,这是我的代码片段:
using MySql.Data.MySqlClient;
List<dynamic> MyList = new List<dynamic>();
using(MySqlConnection con = new MySqlConnection("server=localhost;database=database;user id=user;password=password")){
con.Open();
string sql = "SELECT * FROM Items";
DateTime defaultDate = DateTime.Now;
MySqlCommand cmd = new MySqlCommand(sql,con);
using(MySqlDataReader reader = cmd.ExecuteReader()){
while(reader.Read()){
MyList.Add(new {
Value = reader["Name"] != null ? reader["Name"].ToString() : "",
Date = reader.GetDateTime(reader.GetOrdinal("Date")) != null ? reader.GetDateTime(reader.GetOrdinal("Date")) : defaultDate
});
}
}
con.Close();
}
最佳答案
您可以使用像下面这样的帮助函数(SO 用户 Rein 已经在相关问题 here 中写过),它将为您满足任何数据库类型 可以为 Null。
即
Date = ConvertFromDBVal<DateTime>(reader.GetOrdinal("Date"));
使用泛型函数:
public static T ConvertFromDBVal<T>(object obj)
{
if (obj == null || obj == DBNull.Value) {
return default(T); // returns the default value for the type
}
else
{
return (T)obj;
}
}
关于c# - 如何使用 MySQL Reader 处理空日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405115/