我遇到错误:
ExecuteNonQuery需要打开且可用的连接。
连接的当前状态为打开。
我使用了con.Open();
,但是遇到了同样的错误。
请帮我。
static string connectionString = ConfigurationManager.AppSettings["MessageDB"].ToString();
static SqlConnection _sqlconn = new SqlConnection(connectionString);
public static void Message(MessageLog messageLog)
{
try
{
_sqlconn = new SqlConnection(connectionString);
_sqlconn.Open();
SqlCommand cmd = _sqlconn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "INSERT_MESSAGE";
SqlParameter APPID = cmd.CreateParameter();
APPID.ParameterName = @"@MessageID";
APPID.DbType = DbType.Int16;
APPID.Direction = ParameterDirection.Input;
APPID.Value = messageLog.MessageID;
cmd.Parameters.Add(MessageID);
cmd.ExecuteNonQuery();
_sqlconn.Close();
}
catch (Exception ex)
{
if (_sqlconn.State == ConnectionState.Open)
{
_sqlconn.Close();
}
ExceptionLogger.LogException(ex);
}
}
答案 0 :(得分:0)
恕我直言,您的问题是使用静态连接变量。
static SqlConnection _sqlconn = new SqlConnection(connectionString);
,然后您又重新分配了它,这没有任何意义。我会稍微更改您的代码:
static string connectionString = ConfigurationManager.AppSettings["MessageDB"].ToString();
public static void Message(MessageLog messageLog)
{
using(var _sqlconn = new SqlConnection(connectionString))
{
using(var cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "INSERT_MESSAGE";
cmd.Connection = _sqlconn;
cmd.Parameters.Add("@MessageID", DbType.Int16).Value = messageLog.MessageID;
try
{
if(_sqlconn.State == ConnectionState.Closed) _sqlconn.Open()
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
}
finally
{
if (_sqlconn.State == ConnectionState.Open)
{
_sqlconn.Close();
}
}
}
}
}
该语法的好处?
答案 1 :(得分:-1)
我认为您在此提供商上已有连接 试试这个:
_sqlconn = new SqlConnection(connectionString);
if(_sqlconn .State == ConnectionState.Closed)
_sqlconn.Open();
SqlCommand cmd = _sqlconn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "INSERT_MESSAGE";
SqlParameter APPID = cmd.CreateParameter();
APPID.ParameterName = @"@MessageID";
APPID.DbType = DbType.Int16;
APPID.Direction = ParameterDirection.Input;
APPID.Value = messageLog.MessageID;
cmd.Parameters.Add(MessageID);
cmd.ExecuteNonQuery();
_sqlconn.Close();
}
catch (Exception ex)
{
if (_sqlconn.State == ConnectionState.Open)
{
_sqlconn.Close();
}
ExceptionLogger.LogException(ex);
}