DBNull if statement

前端 未结 9 1535
再見小時候
再見小時候 2020-12-01 13:55

I\'m trying to execute a stored procedure and then use an if statement to check for null values and I\'m coming up short. I\'m a VB guy so please bear with me if I\'m making

相关标签:
9条回答
  • 2020-12-01 13:58

    I use String.IsNullorEmpty often. It will work her because when DBNull is set to .ToString it returns empty.

    if(!(String.IsNullorEmpty(rsData["usr.ursrdaystime"].toString())){
            strLevel = rsData["usr.ursrdaystime"].toString();
        }
    
    0 讨论(0)
  • 2020-12-01 14:00

    Ternary operator should do nicely here: condition ? first_expression : second_expression;

    strLevel = !Convert.IsDBNull(rsData["usr.ursrdaystime"]) ? Convert.ToString(rsData["usr.ursrdaystime"]) : null

    0 讨论(0)
  • 2020-12-01 14:04

    The idiomatic way is to say:

    if(rsData["usr.ursrdaystime"] != DBNull.Value) {
        strLevel = rsData["usr.ursrdaystime"].ToString();
    }
    

    This:

    rsData = objCmd.ExecuteReader();
    rsData.Read();
    

    Makes it look like you're reading exactly one value. Use IDbCommand.ExecuteScalar instead.

    0 讨论(0)
  • 2020-12-01 14:04

    At first use ExecuteScalar

     objConn = new SqlConnection(strConnection);
     objConn.Open();
     objCmd = new SqlCommand(strSQL, objConn);
     object result = cmd.ExecuteScalar();
     if(result == null)
         strLevel = "";
     else 
         strLevel = result.ToString();
    
    0 讨论(0)
  • 2020-12-01 14:10

    Consider:

    if(rsData.Read()) {
      int index = rsData.GetOrdinal("columnName"); // I expect, just "ursrdaystime"
      if(rsData.IsDBNull(index)) {
         // is a null
      } else {
         // access the value via any of the rsData.Get*(index) methods
      }
    } else {
      // no row returned
    }
    

    Also: you need more using ;p

    0 讨论(0)
  • 2020-12-01 14:10
    if(!rsData.IsDBNull(rsData.GetOrdinal("usr.ursrdaystime")))
    {
      strLevel = rsData.GetString("usr.ursrdaystime"); 
    }
    

    http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.isdbnull.aspx

    http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal.aspx

    0 讨论(0)
提交回复
热议问题