//检索数据表获得当前列的最大值
        public int GetMaxDataBase(string tempStrSQL)
        {
            int max = 0;
            this.myConnection = new SqlConnection(connectionString);
           
            SqlCommand tempSqlCommand = new SqlCommand(tempStrSQL, this.myConnection);
            try
            {
                myConnection.Open();
                if (tempSqlCommand.ExecuteScalar().ToString() != null)
                {
                    max = int.Parse(tempSqlCommand.ExecuteScalar().ToString());这里出错了,tempSqlCommand.ExecuteScalar()执行的结果为空,没有记录,请大家指点,我该怎么做呢,谢谢                }
                else
                {
                    max = 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);            }
            return max;
        }

解决方案 »

  1.   

    tempSqlCommand.ExecuteScalar().ToString()可能为String.Empty了
      

  2.   

    //检索数据表获得当前列的最大值
            public int GetMaxDataBase(string tempStrSQL)
            {
                int max = 0;
                this.myConnection = new SqlConnection(connectionString);
               
                SqlCommand tempSqlCommand = new SqlCommand(tempStrSQL, this.myConnection);
                try
                {
                    myConnection.Open();
                    if (tempSqlCommand.ExecuteScalar().ToString() != String.Empty)
                    {
                        max = int.Parse(tempSqlCommand.ExecuteScalar().ToString());
                    }
                    else
                    {
                        max = 0;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);            }
                return max;
            }
    问题解决了,但我不明白,把tempSqlCommand.ExecuteScalar().ToString() != String.Empty写成tempSqlCommand.ExecuteScalar().ToString() != null为什么不对呢?数据库中的查询结果可是null
      

  3.   

    null表示是一个对象是空的。
    DBNull表示是数据表中查询的内容是空的
    String.Empty表示一个空字符串。
      

  4.   

    if (tempSqlCommand.ExecuteScalar() != null)
    tempSqlCommand.ExecuteScalar()的结果是object,这样写出错了呀
      

  5.   

    object o = tempSqlCommand.ExecuteScalar();
    if(o != null)
    {
    ...
    }
      

  6.   

    回楼上的,我使用OBJECT也报错,报的好像是SQLEXCEPTION的错,反正也是不正确的。