在执行以下代码期间,会发生此错误“ExecuteNonQuery需要打开且可用的连接。连接的当前状态已关闭。 [英] During execution of following code this error occurs "ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."
本文介绍了在执行以下代码期间,会发生此错误“ExecuteNonQuery需要打开且可用的连接。连接的当前状态已关闭。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用System.Data;
使用System.Data.SqlClient;
使用System.Configuration;
公共部分类注册:System.Web.UI.Page
{
DBConnection dbcon = new DBConnection();
String constr = System.Configuration.ConfigurationManager.AppSettings [constr]。ToString();
SqlConnection con;
Int16 ucode;
protected void btnregsubmit_Click(object sender,ImageClickEventArgs e)
{
SqlCommand cmd = new SqlCommand();
try
{
con = new SqlConnection(constr);
cmd = new SqlCommand(insertuser,con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(@ usertype,ucode);
cmd.Parameters.AddWithValue(@ sqrtyans,txtans.Text);
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(< script> alert('Data is inserted')< / script>);
}
catch(exception ex)
{
throw ex;
}
}
}
解决方案
我修改你的try块只需复制并粘贴你的代码
试用
{
con = new SqlConnection(constr);
con.Open();
cmd = new SqlCommand( insertuser ,con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue( @ usertype,ucode);
cmd.Parameters.AddWithValue( @ sqrtyans,txtans.Text);
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect( < script> alert('Data is inserted')< / script> 跨度>);
}
你没有打开执行sql查询的连接
using System.Data; using System.Data.SqlClient; using System.Configuration; public partial class Register : System.Web.UI.Page { DBConnection dbcon = new DBConnection(); String constr= System.Configuration.ConfigurationManager.AppSettings["constr"].ToString(); SqlConnection con; Int16 ucode; protected void btnregsubmit_Click(object sender, ImageClickEventArgs e) { SqlCommand cmd = new SqlCommand(); try { con = new SqlConnection(constr); cmd = new SqlCommand("insertuser", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@usertype", ucode); cmd.Parameters.AddWithValue("@sqrtyans", txtans.Text); cmd.ExecuteNonQuery(); con.Close(); Response.Redirect("<script>alert('Data is inserted')</script>"); } catch (Exception ex) { throw ex; } } }
解决方案
i have modify your try block just copy and paste in your code
try { con = new SqlConnection(constr); con.Open(); cmd = new SqlCommand("insertuser", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@usertype", ucode); cmd.Parameters.AddWithValue("@sqrtyans", txtans.Text); cmd.ExecuteNonQuery(); con.Close(); Response.Redirect("<script>alert('Data is inserted')</script>"); }
Your Have not open the connection to execute your sql query
这篇关于在执行以下代码期间,会发生此错误“ExecuteNonQuery需要打开且可用的连接。连接的当前状态已关闭。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文