基本上,当我运行此代码时,我收到以下错误,而且我不知道如何解决它。单击按钮后出现此错误,然后重定向回Visual Studio,出现以下错误。请帮我解决这个错误,感谢帮助。
已经有一个与此命令关联的打开DataReader,必须先关闭它。
public partial class forgot : System.Web.UI.Page
{
protected void resetpass_Click(object sender, EventArgs e)
{
SqlDataReader reader = null;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from reg where Username =@username", con);
cmd.Parameters.AddWithValue("@username", username.Text);
cmd.Parameters.AddWithValue("@security1", sec1.Text);
cmd.Parameters.AddWithValue("@security2", sec2.Text);
reader = cmd.ExecuteReader();
if (reader != null && reader.HasRows)
{
newpass.Visible = true;
confpass.Visible = true;
Label1.Text = "New Password";
Label2.Text = "Confirm New Password";
SqlDataAdapter updates = new SqlDataAdapter("update reg set Password='" + newpass.Text + "'", con);
DataSet ds = new DataSet();
updates.Fill(ds);
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('The Password has been Changed')</script>");
con.Close();
}
}
}
答案 0 :(得分:1)
您收到该错误是因为您有嵌套的数据读取器。这是您的代码,简化,以显示您正在做的事情:
protected void resetpass_Click(object sender, EventArgs e) {
// Here is data reader
SqlDataReader reader = null;
// ...
reader = cmd.ExecuteReader();
if( reader != null && reader.HasRows ) {
// ...
// and here is another one within the above data reader
SqlDataAdapter updates = new SqlDataAdapter( "update reg set Password='" + newpass.Text + "'", con );
}
}
为此,您需要启用MARS。您可以在连接字符串中执行此操作:
Server=.\SQLEXPRESS;Database=master;Integrated Security=SSPI;
MultipleActiveResultSets=true;
当然你只是一个例子,你需要使用自己的连接字符串。
答案 1 :(得分:1)
错误表示您已关闭DataReader
并在关闭SqlDataAdapter
之前又打开了另一个DataReader
。所以在.Net中你需要关闭第一个命令才能打开一个新命令。
改变这个:
if (reader != null && reader.HasRows)
{
newpass.Visible = true;
confpass.Visible = true;
Label1.Text = "New Password";
Label2.Text = "Confirm New Password";
SqlDataAdapter updates = new SqlDataAdapter("update reg set Password='" + newpass.Text + "'", con);
DataSet ds = new DataSet();
updates.Fill(ds);
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('The Password has been Changed')</script>");
con.Close();
}
到
if (reader != null && reader.HasRows)
{
reader.Close();
newpass.Visible = true;
confpass.Visible = true;
Label1.Text = "New Password";
Label2.Text = "Confirm New Password";
SqlDataAdapter updates = new SqlDataAdapter("update reg set Password='" + newpass.Text + "'", con);
DataSet ds = new DataSet();
updates.Fill(ds);
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('The Password has been Changed')</script>");
con.Close();
}
答案 2 :(得分:0)
当您尝试运行Fill
时,连接con
已经忙于尝试检索数据以保持SqlDataReader
满意。数据库连接一次只能处理一个结果集。
您有两种选择:
updates
,因此您将同时打开两个。reader
首先获取完整的结果集,将其存储在数组或DataTable中。然后,当您完成阅读器后,遍历数组/表并执行reg。