gpt4 book ai didi

sql - 如果值为空,如何将值返回到 sqldatareader?

转载 作者:行者123 更新时间:2023-12-02 21:26:42 28 4
gpt4 key购买 nike

我目前正在使用 SQL 数据读取器(在 vb.net 中)通过存储过程从 SQL Server 2008 数据库中提取文章对象。该对象的一部分包括如下所示的两个属性:

theArticle.Truthfulness = ((myReader.GetInt32(myReader.GetOrdinal("Truthfulness"))))
theArticle.Relevance = ((myReader.GetInt32(myReader.GetOrdinal("Relevance"))))

我的问题是真实性和相关性可能会返回空值,这会导致函数失败。

我想我明白为什么。我要求提供一个整数值 (getin32),因为返回 null,所以失败。

如何容纳数据库中的空值以免其掉落?

最佳答案

您可以使用 .IsDBNull() 检查给定序数位置是否为空,然后执行某些操作 - 例如将您的值设置为 -1 或其他值:

int myOrdinal = myReader.GetOrdinal("Truthfullness");

if(myReader.IsDBNull(myOrdinal))
{
theArticle.Truthfulness = -1;
}
else
{
theArticle.Truthfulness = myReader.GetInt32(myOrdinal);
}

正如 Mike Hofer 在他的回答中指出的那样,您还可以将所有这些逻辑包装到扩展方法中:

public static class SqlDataReaderExtensions 
{
public static int SafeGetInt32(this SqlDataReader reader,
string columnName, int defaultValue)
{
int ordinal = reader.GetOrdinal(columnName);

if(!reader.IsDbNull(ordinal))
{
return reader.GetInt32(ordinal);
}
else
{
return defaultValue;
}
}
}

然后只需使用“SafeGetInt32”方法即可:

  theArticle.Truthfulness = myReader.SafeGetInt32("Truthfullness", -1);

马克

关于sql - 如果值为空,如何将值返回到 sqldatareader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1513438/

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