SQL DataReader 如何显示查询中的空值

发布于 2024-08-31 12:58:17 字数 273 浏览 2 评论 0原文

我有一个 DataReader 和一个 StringBuilder (C#.NET),按以下方式使用;

while (reader.Read())
{
    sb.AppendFormat("{0},{1},{2},",reader["Col1"], reader["Col2"], reader["Col3"]);
}

这对我的使用非常有用,但是当一行为空时,我需要它返回“null”,而不仅仅是“”。实现这一目标的好方法是什么?

非常感谢建议

I have a DataReader and a StringBuilder (C#.NET) used in the following way;

while (reader.Read())
{
    sb.AppendFormat("{0},{1},{2},",reader["Col1"], reader["Col2"], reader["Col3"]);
}

Which works great for my use, but when a row is null I need it to return "null", instead of just "". What would be a good way of accomplishing that?

Suggestions are very appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小糖芽 2024-09-07 12:58:17

尝试:

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"));
}

Try:

Convert.IsDBNull(reader["Col1"]) ? "null" : reader["Col1"]

Alternatively, if you're going to be using this repeatedly, this is probably an ideal candidate for a tightly scoped Extension Method, for example:

public static class ExtensionMethods
{
    public static object GetValueOrNull(this SqlDataReader reader, string key)
    {
        return Convert.IsDBNull(reader[key]) ? (object)"null" : reader[key];
    }
}

So you could then write:

var valueOfReader = reader.GetValueOrNull("Col1");

Which would definately make things tidier if you needed to use this logic multiple times inside one StringBuilder.AppendFormat call:

while (reader.Read())
{
    sb.AppendFormat("{0},{1},{2},",reader.GetValueOrNull("Col1"), reader.GetValueOrNull("Col2"), reader.GetvalueOrNull("Col3"));
}
橙幽之幻 2024-09-07 12:58:17
reader["Col1"] == DBNull.Value ? "null" : Convert.ToString(reader["Col1"])
reader["Col1"] == DBNull.Value ? "null" : Convert.ToString(reader["Col1"])
ゃ懵逼小萝莉 2024-09-07 12:58:17
reader.IsDBNull(indexOfColumn) ? "null" : reader[indexOfColumn].ToString();
reader.IsDBNull(indexOfColumn) ? "null" : reader[indexOfColumn].ToString();
娜些时光,永不杰束 2024-09-07 12:58:17
(string)reader["Col1"] ?? "null"
(string)reader["Col1"] ?? "null"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文