2014-02-17 31 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

謝謝!非常感激...!!! –