简单问题,解决给分

siyuan6689 2008-07-07 05:07:29
我在进行用户信息修改的时候出现错误提示“已有打开的与此命令相关联的 DataReader,必须首先将它关闭。”请问如何解决
protected void Submit_Click(object sender, EventArgs e)
{

string strconn = ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(strconn);
conn.Open();
string strsql = "update client set client_name='" + client_name.Text + "',client_pwd='" + client_pwd.Text + "',client_email='" + client_email.Text + "',client_tell='" + client_tell.Text + "',client_company='" + client_company.Text + "',client_vocation='" + client_vocation.Text + "' where client_id='" + Session["client_id"].ToString() + "' ";
SqlCommand cm = new SqlCommand(strsql, conn);
SqlDataReader dr = cm.ExecuteReader();

if (dr.Read())
{
//保存用户权限
Session["client_id"] = dr["client_id"];
}
try
{
cm.ExecuteNonQuery();
Response.Redirect("client_index.aspx?client_id='" + Session["client_id"] + "'");
}
catch (Exception ex)
{

Lbl_note.Text = ex.Message;
Lbl_note.Style["color"] = "red";
}
finally
{
cm.Dispose();
conn.Close();
dr.Close();
}
}
...全文
65 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
GT7466 2008-07-07
  • 打赏
  • 举报
回复
主要原因是 DataReader 在打开使用时,一个 SqlConnection 只允许打开一个 DataReader,在开启另一个 DataReader 时,必须将前面一个先 Close 掉。

在ExecuteNonQuery() 后,内部会生成一个空的 DataReader 对象,并当当前的数据库连接关闭掉后,该 DataReader 才会释放
kkun_3yue3 2008-07-07
  • 打赏
  • 举报
回复
string strconn = ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(strconn);
conn.Open();
string strsql = "update client set client_name='" + client_name.Text + "',client_pwd='" + client_pwd.Text + "',client_email='" + client_email.Text + "',client_tell='" + client_tell.Text + "',client_company='" + client_company.Text + "',client_vocation='" + client_vocation.Text + "' where client_id='" + Session["client_id"].ToString() + "' ";
SqlCommand cm = new SqlCommand(strsql, conn);
SqlDataReader dr = cm.ExecuteReader();

if (dr.Read())
{
//保存用户权限
Session["client_id"] = dr["client_id"];
}
try
{
dr.Close();
cm.ExecuteNonQuery();
Response.Redirect("client_index.aspx?client_id='" + Session["client_id"] + "'");
}
catch (Exception ex)
{

Lbl_note.Text = ex.Message;
Lbl_note.Style["color"] = "red";
}
finally
{
cm.Dispose();
conn.Close();
dr.Close();
}


DR用完就关闭,再用再打开,
金欧 2008-07-07
  • 打赏
  • 举报
回复
try
{
cm.ExecuteNonQuery();
//释放资源.......

Response.Redirect("client_index.aspx?client_id='" + Session["client_id"] + "'");
}
这里先释放资源,再redirect应该就可以了
zzyhuian06142 2008-07-07
  • 打赏
  • 举报
回复
针对你的问题
你在if(dr.Read())上面加个
if(!dr.IsClosed)
{
dr.Close();
}
zzyhuian06142 2008-07-07
  • 打赏
  • 举报
回复
你的是update 语句,又不是Select语句,DataReader能得到值吗?

110,825

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧