2015-12-16 77 views
-2

我一直得到這個錯誤,說我有新的C#,但看了谷歌和教程,仍然不能看到問題是什麼。它可能是一個非常愚蠢的錯誤,但如果有人可以幫助。謝謝:)ExecuteScalar尚未初始化

  // open connection 
      myConnection.Open(); 


      // sql command 
      string Account_Num = txt_acc.Text; 
      string Pin_num = txt_pin.Text; 


      SqlCommand check_details = new SqlCommand("select Account_num, Pin_num from Cust_details where Account_num='" + txt_acc.Text + "'and Pin_num ='" + txt_pin.Text + "'"); 
      check_details.Parameters.AddWithValue("@Account_num", txt_acc.Text); 
      check_details.Parameters.AddWithValue("@Pin_num", txt_pin.Text); 


      int result = Convert.ToInt32(check_details.ExecuteScalar()); 

      if (result > 0) 
      { 
       Console.WriteLine("user exists"); 
      } 


      else 
      { 
       Console.WriteLine("error"); 
      } 
     } 
+0

也許如果你已經搜索了網絡上的_actual_異常,你會發現[重複](http://stackoverflow.com/questions/10263094/executenonquery-connection-property-has-not-been-初始化)。 :) – CodeCaster

+0

您需要爲您的命令提供連接名稱。另外,當你在參數中添加它們時,爲什麼要在查詢中添加acco_num和pin_num? –

回答

1

看起來你沒有連接你的命令。只需將其設置爲Connection propertymyConnection即可。

check_details.Connection = myConnection; 

,或者你可以把它放在你的SqlCommand構造函數作爲第二個參數;

SqlCommand check_details = new SqlCommand("yourCommand", myConnection); 

,或者您可以使用您的連接CreateCommand method;

SqlCommand check_details = myConnection.CreateCommand(); 

而你被誤解了parameterized queries。你仍然在你的SQL查詢中做字符串連接,但你嘗試添加參數。這沒有意義。

使用using statement也會自動處理您的連接和命令。

也儘量不要使用AddWithValueIt may generate unexpected and surprising results sometimes。使用Add方法重載指定您的參數類型及其大小。

using(var myConnection = new SqlConnection(conString)) 
using(var check_details = myConnection.CreateCommand()) 
{ 
    check_details.CommandText = @"select Account_num, Pin_num from Cust_details 
            where Account_num = @accnum 
            and Pin_num = @pinnum"; 
    // I assume your column types as Int 
    check_details.Parameters.Add("@accnum", SqlDbType.Int).Value = int.Parse(txt_acc.Tex); 
    check_details.Parameters.Add("@pinnum", SqlDbType.Int).Value = int.Parse(txt_pin.Text); 
    myConnection.Open(); 
    int result = (int)check_details.ExecuteScalar(); 
    ... 
} 

順便說一句,有沒有點在你的命令來選擇Pin_num列,因爲ExecuteScalar忽略它。