在使用Command.ExecuteNonQuery方法执行SQL时提示以下错误:
there is already an open DataReader associated with this Connection which must be closed first.
在网上查了一下,是因为该方法执行SQL语句的时候默认开启的一个DataReader对象没关闭导致的,网上介绍的都是使用新建连接执行并在执行之后销毁该连接的方法来解决,但我现在必须使用事务管理,两者好像有点冲突。
如下方法:
public int ExecuteNonQuery(IDbCommand command)
{
lock (ADOSession.objLocked)
{
command.CommandTimeout = 15 * 60;
try
{
//using (MySqlConnection conn = new MySqlConnection(config.ConnectionString))
//{
// command.Connection = conn;
if (command.Connection.State == ConnectionState.Closed)
{
command.Connection.Open();
}
return command.ExecuteNonQuery();
//}
}
catch (Exception e)
{
throw new Exception(e.Message + "\n" + command.CommandText);
}
}
}
如果不考虑事务的情况下,将以上代码的注释部分取消注释,可有效避免出现题中的错误。但现在要求必须保证数据完整性而使用了事务,如果使用using并使用新建连接来执行该语句,那么该语句将不在事务控制中,即使是强制为command添加了Transaction,也不会使其处于事务中。这种情况该如何处理?
int row = 0;
using(SqlConnection conn = new SqlConnection(connectionString)){
SqlTransaction tran = conn.BeginTransaction("insert a row");
SqlCommand command = new SqlCommand(strSql, conn);
row = command.ExecuteNonQuery();
command.Dispose();
tran.Commit();
conn.Close();
conn.Dispose();
}
return row;
public void RunSQL(){
var transaction = conn.BeginTransaction();
try{
if(ExecuteNonQuery(command)>0){
ExecuteNonQuery(command1);
ExecuteNonQuery(command2);
ExecuteNonQuery(command3);
......
}else{
ExecuteNonQuery(command4);
ExecuteNonQuery(command5);
ExecuteNonQuery(command6);
.......
}
transaction.Commit();
}catch(Exception e){
transaction.Rollback();
}
}
public int ExecuteNonQuery(IDbCommand command){
......
}
类似于以上的代码吧
有没有尝试过执行完一次就将对应的DataReader关闭
望采纳,谢谢
这个DataReader 应该有一个close();方法吧,每次执行完sql,关闭。