急!已有打开的与此命令相关联的 DataReader,必须首先将它关闭。 asp.net
源代码:public partial class forget_psw2 : System.Web.UI.Page
{
string conStr = "server=.\\sqlexpress;database=User;uid=sa;pwd=123;";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(conStr);
con.Open();
string sqlQuery = "select * from userinfo where userName='" + Request.Params["id"].ToString() + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
TextBox1.Text = dr["question"].ToString();
}
dr.Close();
con.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//一个连接只能打开一个datareader
SqlConnection con = new SqlConnection(conStr);
con.Open();
string sqlQuery = "select * from userinfo where userName='" + Request.Params["id"].ToString() + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (TextBox2.Text.Trim() == dr["answer"].ToString().Trim())
{
//Response.Redirect("forget_psw2.aspx?id='" + Request.Params["id"].ToString() + "");
sqlQuery = "update userinfo set password = '" + TextBox3.Text + "'";
cmd.CommandText = sqlQuery;
if (cmd.ExecuteNonQuery() > 0)
{
this.Response.Write(" <script language=javascript>alert('修改密码成功!');</script> ");
}
else
{
this.Response.Write(" <script language=javascript>alert('修改失败!');</script> ");
}
}
else
{
this.Response.Write(" <script language=javascript>alert('回答错误!');</script> ");
TextBox2.Text = "";
TextBox3.Text = string.Empty;
}
}
con.Close();
dr.Close();
} --------------------编程问答-------------------- 你只是在测试的吧?
在实际应用中,一般访问数据都有公共的方法,连接数据是一个方法,执行sql语句,查询语句,执行存储过程等,都有单独的方法.
当然每次访问数据完后,都要关闭连接
--------------------编程问答-------------------- Reader读取数据完成后,必须先关闭。而且连接数据库不应该放在Web.config里面吗? --------------------编程问答--------------------
是交作业而已,实际是要有架构的吧 --------------------编程问答--------------------
我都是用语句连接,在Web.config总是错误,不知道怎么连,也感觉没必要.Reader已经关闭了啊 --------------------编程问答-------------------- 肯定是哪里写错了,Web.Config报什么错误 --------------------编程问答-------------------- 错误是"已有打开的与此命令相关联的 DataReader"
补充:.NET技术 , ASP.NET