SQL数据读取器

编程入门 行业动态 更新时间:2024-10-23 21:32:38
本文介绍了SQL数据读取器 - 处理空列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用一个SqlDataReader从数据库建立波苏斯。在code工作时,遇到在数据库中的空值除外。例如,如果在数据库中的名字列包含空值,则会引发异常。

I'm using a SQLdatareader to build POCOs from a database. The code works except when it encounters a null value in the database. For example, if the FirstName column in the database contains a null value, an exception is thrown.

employee.FirstName = sqlreader.GetString(indexFirstName);

什么是在这种情况下,以处理空值的最佳方式?

What is the best way to handle null values in this situation?

推荐答案

您需要检查 IsDBNull以便:

if(!SqlReader.IsDBNull(indexFirstName)) { employee.FirstName = sqlreader.GetString(indexFirstName); }

这是你唯一的检测和处理这种情况可靠的方法。

That's your only reliable way to detect and handle this situation.

我包这些东西到扩展方法,而且往往返回默认值如果列确空:

I wrapped those things into extension methods and tend to return a default value if the column is indeed null:

public static string SafeGetString(this SqlDataReader reader, int colIndex) { if(!reader.IsDBNull(colIndex)) return reader.GetString(colIndex); return string.Empty; }

现在你可以这样调用它:

Now you can call it like this:

employee.FirstName = SqlReader.SafeGetString(indexFirstName);

,你就再也不必担心异常或空值。

更多推荐

SQL数据读取器

本文发布于:2023-10-26 09:39:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529784.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:读取器   数据   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!