After ExecuteScalar: Object reference not set etc

前端 未结 3 1759
醉酒成梦
醉酒成梦 2021-01-18 14:32

What code I should add to accept null from WHERE statement.

{
    int numApprovals = 0;
    string sql = \"SELECT COUNT(Type) AS OpenforApproval \" +
                


        
3条回答
  •  梦毁少年i
    2021-01-18 15:29

    The problem is probably the direct cast to int. This throws an exception if cmd.ExecuteScalar() returns null. You need to decide what to return in that case. For this example I am returning 0 if cmd.ExecuteScalar() returns null

    using (cn = new SqlConnection(ConnectionString()))
    {
        cn.Open();
        using (cmd = new SqlCommand(sql, cn))
        {
            cmd.CommandType = CommandType.Text;
            object result = cmd.ExecuteScalar();
            numApprovals = result == null ? 0 : (int)result;
        }
    }
    
    return numApprovals;
    

提交回复
热议问题