首先我将一个新成员插入到成员表中。然后我查询表以获取会员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;
}
答案 0 :(得分: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;
}
答案 1 :(得分:0)
非常仔细地阅读错误消息。它与ExecuteScalar太快无关,也与操作顺序无关,除非特别是缺少操作。 您尚未打开连接。
在connection.Open();
调用之前的using
块范围内放入ExecuteScalar
,您应该会遇到不同的结果。
答案 2 :(得分: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上应用它时需要使用sql命令。在执行命令之前,您错过了打开连接。