日期:2014-05-17  浏览次数:20612 次

ExecuteScalar 的返回值 是 未定义的值?
SqlCommand com = new SqlCommand("select name from mytest where name='test');
object temp_object= com.ExecuteScalar();  
com.Dispose();  
   
//再对temp_object进行判断  
if(temp_object!=System.DBNull.Value || object_temp1!=null)
{
  int nCount = Convert.ToInt32(temp_object.ToString());//程序执行到此处错误
  ......
}

调试发现 temp_object的值是 未定义的值

为什么if语句还会执行。
未定义的值 如何理解


------解决方案--------------------
你这样肯定会出错的呀!字段类型都没搞清楚!
C# code

SqlCommand com = new  SqlCommand("select count(name) from mytest where  name='test'); 
int  temp_object= Convert.toInt32(com.ExecuteScalar());  
com.Dispose();   
if(temp_object>0) 
{ 
    int nCount =temp_object;
    ...... 
}

------解决方案--------------------
select name from mytest where name='test'
你这个查询根本不是标量查询,为何要用com.ExecuteScalar();

ExecuteScalar此方法只是返回一个object类型,只能判断是否为null.

如果执行如count(*)这样的查询,可以做这样的转换Convert.toUint(com.ExecuteScalar())
------解决方案--------------------
C# code
//再对temp_object进行判断  
if(object_temp1!=null) 
{ 
    int nCount = Convert.ToInt32(temp_object.ToString());//程序执行到此处错误 
    //...... 
}

------解决方案--------------------
name 是int類型的嗎?
------解决方案--------------------
sql 语句的问题吧
select count(*)from mytest where name='test'
------解决方案--------------------
这段程序上有很多问题啊;
1.如果你查询的字段是NAME,那么是STRING,后面怎么转成INT,当然会出问题.
2.如果你查询的是总数,你的SQL语句就是错的.
3.object_temp1是什么东西,写错了?