2014-10-01 90 views
0

我有以下的功能,它檢查以查看是否用戶(strU)在表中的列存在,如果是這樣返回1,否則返回0:爲什麼的ExecuteScalar返回的NullReferenceException錯誤

public int AddDataScalar(string strU) 
{ 
    string strQueryExistence = "SELECT 1 FROM [OB].[h].[OP_PEONS] WHERE Executive= '" + strU + "'"; 
    int inNum; 
    using (SqlConnection con = new SqlConnection(strConn)) 
    { 
     con.Open(); 
     SqlCommand cmd = new SqlCommand(strQueryExistence, con); 
     object value = cmd.ExecuteScalar().ToString(); 
     if (value != null) 
     { 
      inNum = 1; 
     } 
     else 
     { 
      inNum = 0; 
     } 
     con.Close(); 
    } 
    return inNum; 
} 

它是未能在這一行:object value = cmd.ExecuteScalar().ToString();

,出現以下錯誤:Object reference not set to an instance of an object.

我該如何解決呢?

+0

http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and怎麼辦我修好了 – 2014-10-01 14:34:19

回答

1

如果您的WHERE條件不產生任何結果,則ExecuteScalar返回null。
如果您在ExecuteScalar返回null時應用任何類型的轉換,則會遇到問題。

說,我真的建議一些更改查詢

public int AddDataScalar(string strU) 
{ 
    string strQueryExistence = @"IF EXISTS(SELECT 1 FROM [OB].[h].[OP_PEONS] 
           WHERE Executive= @stru) SELECT 1 ELSE SELECT 0"; 
    int inNum = 0; 
    using (SqlConnection con = new SqlConnection(strConn)) 
    using (SqlCommand cmd = new SqlCommand(strQueryExistence, con)) 
    { 
     con.Open(); 
     cmd.Parameters.AddWithValue("@stru", strU); 
     inNum = Convert.ToInt32(cmd.ExecuteScalar()); 
    } 
    return inNum; 
} 

的第一件事是IF EXISTS噸-SQL的功能是發現,如果一個特定的記錄表中​​的存在與否的最快方式。第二點是使用參數化查詢來避免解析問題和Sql Injection場景。

如果存在則語句可以確保的ExecuteScalar沒有返回null,因爲在這種情況下,ELSE部分將返回零

+0

謝謝。我編輯了缺失的''' – SearchForKnowledge 2014-10-01 14:42:33

+1

的代碼,在這種情況下,不需要三元運算符,所以我已經刪除它。 – Steve 2014-10-01 14:43:48

+0

所以如果用戶不在'Executive'列中,函數將返回0,否則返回1? – SearchForKnowledge 2014-10-01 15:33:29

1

如果objectcmd.ExecuteScalar()返回爲null,您將得到此例外。使用方法:

string value = System.Convert.ToString(cmd.ExecuteScalar()); 

如果您需要將結果轉換爲string

1

每當cmd.ExecuteScalar()回報然後null.ToString()拋出異常。 在你的情況下,只需使用特雷納裏操作

inNum = cmd.ExecuteScalar() == null ? 0 : 1; 

的實施可能是

public int AddDataScalar(string strU) { 
    using (SqlConnection con = new SqlConnection(strConn)) { 
    con.Open(); 

    // Make your SQL readable: use @"" strings 
    strQueryExistence = 
     @"SELECT 1 
      FROM [OB].[h].[OP_PEONS] 
     WHERE Executive = @prm_Executive"; 

    // using is a better practice 
    using (SqlCommand cmd = new SqlCommand(strQueryExistence, con)) { 
     // parameters are better than hardcoding 
     cmd.Parameters.AddWithValue("@prm_Executive", strU); 

     return cmd.ExecuteScalar() == null ? 0 : 1; 
    } 
    } 
} 
+0

謝謝你的編輯。 – SearchForKnowledge 2014-10-01 14:44:58

+0

如果用戶不存在於「Executive」列中,我想返回0,否則返回1如果用戶存在。 – SearchForKnowledge 2014-10-01 15:01:31

相關問題