2014-02-17 28 views
0

伙计们,我需要一点帮助。这是我第一次开发一个有DB的应用程序,考虑到这一点,请原谅我的错误。ExecuteScalar:对象引用未设置等

我想从数据库中获取一个布尔值,并应用if,否则循环它......但它一直在ExecuteScalar函数上抛出“Object reference not set”错误。

下面是代码: -

 string sql = " // here is my sql query "; 
     string connectionstring = " // Here is my connection string.... "; 
     SqlConnection connection = new SqlConnection(connectionstring); 
     SqlCommand command = new SqlCommand(sql,connection); 
     command.Connection = connection; 
     connection.Open(); 
     bool ev = (bool)command.ExecuteScalar(); 
     if (ev == true) 
     { 
      MessageBox.Show("some error"); 
     } 
     else 
     { 
      // Some Code 
     } 

我在做什么错?

帮助将非常感激。

问候。

+0

你检查了返回值吗?这可能是因为它没有连接或什么。 – joell

回答

2

大概查询返回null。试试这个:

bool? ev = (bool?)command.ExecuteScalar(); 

if(ev.GetValueOrDefault(false)) 
{ 
    MessageBox.Show(...); 
} 

?意味着空的,所以这种方式从查询返回的值允许是null

+0

+1 Good catch ... –

+0

谢谢你,你的回答似乎合乎逻辑,但我似乎无法应用你的方法。 如果在ev中返回的值为null,我想执行一些任务。我该如何去做呢?如果返回的值是1,我想显示带有“已添加”文本的消息框。 –

+0

删除'GetValueOrDefault'部分。检查'HasValue'。那么你可以检查'ev == null'。 –

0

做了ExecuteScalar返回值一些验证如下

using(SqlConnection connection = new SqlConnection(connectionstring)) 
using(SqlCommand command = new SqlCommand(sql,connection)) 
{ 
    connection.Open(); 
    object ev = command.ExecuteScalar(); 
    bool flag; 
    if(ev!=null) 
    { 
     // return as null value, do Task 1 
    }else if(Boolean.TryParse(ev.ToString(), out flag) && flag) 
    { 
     // return as true value, do Task 2 
    } 
    }else 
    { 
     // return as false value, do Task 3 
    } 
} 
+0

Yup“ev”返回null,因为在我检索的特定列中没有任何内容。 如果ev为null,我该如何应用一些代码?就像我想显示一个消息框说EV是空的。 –

0

帕特里克的评论是现货。这里有一个完整的例子...

string sql = " // here is my sql query "; 
string connectionstring = " // Here is my connection string.... "; 

using (SqlConnection connection = new SqlConnection(connectionstring)) 
using (SqlCommand command = new SqlCommand(sql,connection)) 
{ 
    connection.Open(); 
    bool? ev = (bool?)command.ExecuteScalar(); 

    if (ev.HasValue == true && ev.Value == true) 
    { 
     MessageBox.Show("some error"); 
    } 
} 
+0

谢谢!非常感激...!!! –