我有一个 DataReader 和一个 StringBuilder (C#.NET),按以下方式使用;
while (reader.Read())
{
sb.AppendFormat("{0},{1},{2},",reader["Col1"], reader["Col2"], reader["Col3"]);
}
这对我的使用非常有用,但是当一行为空时,我需要它返回“null”,而不仅仅是“”。实现该目标的好方法是什么?
非常感谢您的建议
最佳答案
尝试:
Convert.IsDBNull(reader["Col1"]) ? "null" : reader["Col1"]
或者,如果您要重复使用它,这可能是一个范围很窄的扩展方法的理想选择,例如:
public static class ExtensionMethods
{
public static object GetValueOrNull(this SqlDataReader reader, string key)
{
return Convert.IsDBNull(reader[key]) ? (object)"null" : reader[key];
}
}
所以你可以这样写:
var valueOfReader = reader.GetValueOrNull("Col1");
如果您需要在一次 StringBuilder.AppendFormat
调用中多次使用此逻辑,这肯定会使事情变得更整洁:
while (reader.Read())
{
sb.AppendFormat("{0},{1},{2},",reader.GetValueOrNull("Col1"), reader.GetValueOrNull("Col2"), reader.GetvalueOrNull("Col3"));
}
关于c# - SQL DataReader 如何显示查询中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2773155/