检查列是否返回空值的最佳方法(从数据库到.net应用程序)

我有一个带有DateTime列的表,该列可以具有NULL值

现在我使用ODBC连接连接到数据库,并将值传入.net / c#中的DataTable。

我可以通过去检查它是否为NULL

if(String.IsNullOrEmpty(table.rows[0][0].ToString()) { //Whatever I want to do } 

String.IsNullOrEmpty是检查空值的正确方法。

在对象上使用DBNull.Value.Equals而不将其转换为字符串。

这是一个例子:

  if (! DBNull.Value.Equals(row[fieldName])) { //not null } else { //null } 

只需使用DataRow.IsNull 。 它已覆盖接受列索引列名称DataColumn对象作为参数。

使用列索引的示例:

 if (table.rows[0].IsNull(0)) { //Whatever I want to do } 

虽然该函数被称为IsNull但它确实与DbNull进行了比较(这正是您所需要的)。


如果我想检查DbNull但我没有DataRow怎么办? 使用Convert.IsDBNull 。

 System.Convert.IsDbNull][1](table.rows[0][0]); 

IIRC, (table.rows[0][0] == null)将不起作用,因为DbNull.Value != null;

row.IsNull( “列”)

如果我们使用EF并在while循环中读取数据库元素那么,

  using( var idr = connection, SP.......) { while(idr.read()) { if(Sting.ISNullOrEmpty(idr["ColumnNameFromDB"].ToString()) //do something } } } 

检查一下

 if(table.rows[0][0] == null) { //Whatever I want to do } 

或者你可以

 if(t.Rows[0].IsNull(0)) { //Whatever I want to do }