gpt4 book ai didi

.net - 在 .net4 中使用具有 dbnull 值的 datareader

转载 作者:行者123 更新时间:2023-12-02 05:07:19 25 4
gpt4 key购买 nike

我听说框架4中有一个字段扩展方法,允许从数据读取器接收空值,而不必经历第一次测试如果不为空则...等等的过程。有关于扩展方法的信息这里( MSDN ),但我不知道如何在代码中使用它(我对.net相对较新,以前从未使用过扩展方法)。如果有人能举个例子,我将不胜感激。

这是我尝试实现的,但当任一列中返回 dbnull 时,它会返回错误。

Reader.Read()
Dim Val As Nullable(Of Double) = Reader.GetDecimal(0)
Dim Vol As Nullable(Of Long) = Reader.GetInt32(1)

最佳答案

这些扩展方法与DataRow相关 - 即DataTable...不是IDataReader(等等)。不过,您可以在此处使用条件执行您想要的操作 - 在 VB 或 C# 中为 IIf:

double? val = reader.IsDBNull(index) ? (double?) null : reader.GetDouble(index);
long? vol = reader.IsDBNull(index) ? (long?)null : reader.GetInt64(index);

您当然可以将它们包装为实用方法,也许作为 IDataReader 上您自己的自定义扩展方法:

public static class DataReaderExtensions
{
public static int? ReadNullableInt32(this IDataReader reader, int index)
{
return reader.IsDBNull(index) ? (int?)null : reader.GetInt32(index);
}
public static long? ReadNullableInt64(this IDataReader reader, int index)
{
return reader.IsDBNull(index) ? (long?)null : reader.GetInt64(index);
}
public static double? ReadNullableDouble(this IDataReader reader, int index)
{
return reader.IsDBNull(index) ? (double?)null : reader.GetDouble(index);
}
public static string ReadNullableString(this IDataReader reader, int index)
{
return reader.IsDBNull(index) ? null : reader.GetString(index);
}
// etc
}

(很抱歉使用 C# 作为示例 - 但您阅读 C# 的能力可能比我写 vb.net 的准确还要好)

关于.net - 在 .net4 中使用具有 dbnull 值的 datareader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9464179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com