0

首先我将一个新成员插入到成员表中。然后即时查询表以取回成员 ID。我将数据放入表中,但它出现的速度不够快,无法在以下几行中进行查询。

我收到此异常“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; 

   }
4

3 回答 3

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; 
}
于 2011-12-03T04:57:35.117 回答
0

仔细阅读错误信息。它与 ExecuteScalar 太快无关,也与操作顺序无关,除非特别是缺少一个操作。您尚未打开连接。

在调用之前connection.Open();在块的范围内折腾,您应该会遇到不同的结果。usingExecuteScalar

于 2011-12-03T04:54:01.070 回答
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 语句用于自动处理连接,当您已经在 SqlConnection 上应用它时,我认为这里不需要使用 with sql 命令。而且您在执行命令之前错过了打开连接。

于 2011-12-03T05:07:39.463 回答