如何对null值进行处理呢?imaxid = (int)command.ExecuteScalar();
如下,如果sql执行后,返回的是null,如何处理呢?
正常下,下面的sql返回的是 一个 int 值,但是如果取不到记录时,
imaxid = (int)command.ExecuteScalar(); 就会报错,
如何进行容错处理呢?
        //取交书地点 orderid
        public int GetOrderId(string strkehu)
        {
            int imaxid;
            strsql = " select max(orderid) as maxid from cp_交书地点 where 客户编码='" + strkehu + "'";
            command = new SqlCommand(strsql, mydb.conn);
            imaxid = (int)command.ExecuteScalar();
            return imaxid;
        }

解决方案 »

  1.   

    object x = command.ExecuteScalar();
    if(x!=null)
    imaxid = (int)x;
      

  2.   


     //取交书地点 orderid
            public int GetOrderId(string strkehu)
            {
                strsql = " select max(orderid) as maxid from cp_交书地点 where 客户编码='" + strkehu + "'";
                command = new SqlCommand(strsql, mydb.conn);
                int imaxid = command.ExecuteScalar()!=null?(int)command.ExecuteScalar():0;
                return imaxid;
            }
      

  3.   

    4楼的写法有个问题就是非空时ExecuteScalar会执行两次造成不必要的消耗,写法上可以用1楼的。
    也可以用 int? 而不是int,不过一般不必要。
      

  4.   

    //取交书地点 orderid
            public int GetOrderId(string strkehu)
            {
                int? imaxid = null;
                strsql = " select max(orderid) as maxid from cp_交书地点 where 客户编码='" + strkehu + "'";
                command = new SqlCommand(strsql, mydb.conn);
                imaxid = (int?)command.ExecuteScalar();
                return imaxid == null ? -1 : (int)imaxid;
            }