SqlDataReader.IsDBNull(Int32) 方法

定义

获取一个值,该值指示列中是否包含不存在的或缺少的值。

public:
 override bool IsDBNull(int i);
public override bool IsDBNull (int i);
override this.IsDBNull : int -> bool
Public Overrides Function IsDBNull (i As Integer) As Boolean

参数

i
Int32

从零开始的列序号。

返回

如果指定的列值等效于 DBNull,则为 true;否则为 false

实现

注解

调用此方法以在调用类型化 get 方法之前检查 null 列值, (例如、 GetByteGetChar等) ,以避免引发错误。

using Microsoft.Data.SqlClient;

class Program
{
    static void Main(string[] args)
    {

        using (var connection = new SqlConnection(@"Data Source=(local);Initial Catalog=AdventureWorks2012;Integrated Security=SSPI"))
        {
            var command = new SqlCommand("SELECT p.FirstName, p.MiddleName, p.LastName FROM HumanResources.Employee AS e" +
                                    " JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID;", connection);
            connection.Open();
            var reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.Write(reader.GetString(reader.GetOrdinal("FirstName")));
                // display middle name only of not null
                if (!reader.IsDBNull(reader.GetOrdinal("MiddleName")))
                    Console.Write(" {0}", reader.GetString(reader.GetOrdinal("MiddleName")));
                Console.WriteLine(" {0}", reader.GetString(reader.GetOrdinal("LastName")));
            }
            connection.Close();
        }
    }
}

适用于