2011-12-03 50 views
0

首先將新成員插入到成員表中。然後,即時查詢表以獲取成員標識。我將數據輸入到表格中,但沒有足夠快的速度在下面的行中進行查詢。執行順序或ExecuteScalar問題

我得到這個異常「ExecuteScalar需要一個開放和可用的連接,連接的當前狀態是關閉的。」我無法弄清楚這裏有什麼不對。

//This code works fine 
//Insert new members data 
InsertMembers insert = new InsertMembers(); 
int age = Int32.Parse(txtAge.Text); 
insert.InsertNewMember(txtEmail.Text, Myguid, txtName.Text, txtCity.Text, txtState.Text, txtDescription.Text, age, gender); 

//This is the block thats failing 
//Get Member Id to Insert into Pictures table 
GetMemberInfo GetID = new GetMemberInfo(); 
int UMemberId = GetID.GetMemberId(Myguid); 
Displayme.Text = UMemberId.ToString(); 



public int GetMemberID(string guid) 
    { 
     string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"]; 
     string StrSql = "SELECT MemberID FROM MEMBERS WHERE (Guid = @GuidID)"; 

     int memberId; 
     using (var connection = new SqlConnection(strConectionString)) 
     using (var command = new SqlCommand(StrSql, connection)) 
     { 
      command.Parameters.Add("@GuidID", SqlDbType.VarChar).Value = guid; 
      memberId = (int)command.ExecuteScalar(); 
     } 
     //returns 0 when it should be member id number 
     return memberId; 

    } 

回答

0

請仔細閱讀錯誤消息。它與ExecuteScalar太快無關,也不與操作順序有關,除非有特別的操作缺少您尚未打開連接。

在調用ExecuteScalar之前塊的範圍內折騰connection.Open();,您應該會遇到不同的結果。

+0

謝謝,這是正確的。 – CsharpBeginner

1

你應該叫connection.Open(),在執行命令之前:

public int GetMemberID(string guid) 
{ 
    string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"]; 
    string StrSql = "SELECT MemberID FROM MEMBERS WHERE (Guid = @GuidID)"; 

    int memberId; 
    using (var connection = new SqlConnection(strConectionString)) 
    { 
     connection.Open(); 
     using (var command = new SqlCommand(StrSql, connection)) 
     { 
      command.Parameters.Add("@GuidID", SqlDbType.VarChar).Value = guid; 
      memberId = (int)command.ExecuteScalar(); 
     } 
    } 

    //returns 0 when it should be member id number 
    return memberId; 
} 
0

更換你的這些代碼行

using (var connection = new SqlConnection(strConectionString)) 
     using (var command = new SqlCommand(StrSql, connection)) 
     { 
      command.Parameters.Add("@GuidID", SqlDbType.VarChar).Value = guid; 
      memberId = (int)command.ExecuteScalar(); 
     } 

這些

using (SqlConnection connection = new SqlConnection(
       strConectionString)) 
    { 
     SqlCommand command = new SqlCommand(StrSql, connection); 
     command.Parameters.Add("@GuidID", SqlDbType.VarChar).Value = guid; 
     command.Connection.Open(); 
     memberId = (int)command.ExecuteScalar(); 
    } 
using語句

用於處置自動連接,我不認爲這裏是需要申請使用智慧h sql命令,當你已經將它應用於SqlConnection時。在執行命令之前,您錯過了打開連接的信息。

+0

有意見和反對意見,但作爲一般的經驗法則,你可能會說「如果它實現了IDisposable *(並且你創建了它)*調用Dispose」 - 所以原始代碼是正確的。 –