我在本地服务器上遇到此错误,当遇到此错误时,我重新上传该相关的类文件。在这个问题解决后但不是永久性的。
错误:
executenonquery需要一个开放且可用的连接。该 连接的当前状态是打开的。
代码:
int n;
try
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = DataConnection.Con;
cmd.CommandText = "sp_InsertUpdateDeleteValidationDate";
cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 0;
cmd.Parameters.AddWithValue("@Task", "CheckExist");
cmd.Parameters.AddWithValue("@id", 0);
cmd.Parameters.AddWithValue("@AdId", "");
cmd.Parameters.AddWithValue("@Username", "");
cmd.Parameters.AddWithValue("@DOE", DOE);
cmd.Parameters.AddWithValue("@ExpieryDate", DateTime.Now);
cmd.Parameters.AddWithValue("@DOR", DateTime.Now);
cmd.Parameters.Add("@flag", SqlDbType.Int).Direction = ParameterDirection.Output;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
cmd.ExecuteNonQuery();
n = Convert.ToInt32(cmd.Parameters["@flag"].Value);
return n;
}
}
catch (SqlException Ex)
{
return 0;
}
答案 0 :(得分:3)
您只在DataConnection
课程中创建一个连接。您应该为每个数据库调用创建一个新连接,并让驱动程序的连接池负责有效地重用它们。
将您的DataConnection类更改为:
public class DataConnection
{
public static SqlConnection Con
{
get
{
return new SqlConnection(ConfigurationManager
.ConnectionStrings["conn"].ConnectionString);
}
}
}
并在使用连接时使用using语句,如ekad的答案:
using (SqlConnection conn = DataConnection.Con)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
//use the command here
}
}
答案 1 :(得分:0)
您的SqlConnection
似乎永远不会关闭。尝试使用using statement确保在执行SqlConnection
cmd.ExecuteNonQuery()
int n;
try
{
using (SqlConnection conn = DataConnection.Con)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "sp_InsertUpdateDeleteValidationDate";
cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 0;
cmd.Parameters.AddWithValue("@Task", "CheckExist");
cmd.Parameters.AddWithValue("@id", 0);
cmd.Parameters.AddWithValue("@AdId", "");
cmd.Parameters.AddWithValue("@Username", "");
cmd.Parameters.AddWithValue("@DOE", DOE);
cmd.Parameters.AddWithValue("@ExpieryDate", DateTime.Now);
cmd.Parameters.AddWithValue("@DOR", DateTime.Now);
cmd.Parameters.Add("@flag", SqlDbType.Int).Direction = ParameterDirection.Output;
conn.Open();
cmd.ExecuteNonQuery();
n = Convert.ToInt32(cmd.Parameters["@flag"].Value);
return n;
}
}
}
catch (SqlException Ex)
{
return 0;
}