繁体   English   中英

C#:已经有与此命令关联的打开的DataReader

[英]C# : there is already an open DataReader associated with this command

我目前在单个方法中有多个SqlDataReader和命令的问题。 此方法应删除客户及其相关地址,网络,ipaddresss ...

当我执行代码时,出现错误

已经有与此命令关联的打开的DataReader,必须首先关闭

所以我在Google上搜索了一下,

using(SqlDataReader....)

并在连接字符串中添加MultipleActiveResultSets=True应该会有所帮助。

我正在使用SQL Server 2014,听说SQL Server 2005有问题,所以不应该是问题。

但这仍然行不通...

抛出异常

var addressId = (int)command.ExecuteScalar();

连接字符串:

Data Source=.\\DATABASE;Initial Catalog=customer;Persist Security Info=True;MultipleActiveResultSets=True;User ID=sa;Password=xxxxxxxx!

码:

public static Boolean ExecuteDeleteCutomer(string customerId) {
    using (SqlConnection connection = new SqlConnection(new DatabaseConnection().ConnectionString)) {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;
        SqlDataReader locationReader;
        SqlDataReader networkReader;
        SqlDataReader ipaddressReader;

        // Start a local transaction to delete a customer and related table entries.
        transaction = connection.BeginTransaction("StartTransaction DeleteCustomer");

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try {
            //First get the locations of selected customer
            command.Parameters.AddWithValue("@customerId", customerId);
            command.CommandText =
                    "SELECT l_id from location where c_id = @customerId";
            locationReader = command.ExecuteReader();

            using (locationReader) { //save location ids in a reader
                while (locationReader.Read()) {
                    var locationID = locationReader.NextResult();
                    command.Parameters.AddWithValue("@locationId", locationID);
                    command.CommandText =
                        "SELECT a_id from address where l_location = @locationId";
                    var addressId = (int)command.ExecuteScalar(); // get address ID to delete later

                    command.Parameters.AddWithValue("@addressId", addressId);
                    command.CommandText = "SELECT n_id from network where n_location = @locationId";

                    using (networkReader = command.ExecuteReader()) { // save networks in a reader;
                        while (networkReader.Read()) {
                            var networkId = networkReader.NextResult();
                            command.Parameters.AddWithValue("@networkId", networkId);
                            command.CommandText = "SELECT ip_id from ipaddress where n_id = @networkId";

                            using (ipaddressReader = command.ExecuteReader()) { // get ipaddressId ID to delete later
                                while (ipaddressReader.Read()) {
                                    var ipaddressId = ipaddressReader.NextResult();
                                    command.Parameters.AddWithValue("@ipId", ipaddressId);
                                    command.CommandText = "Delete from ipaddress where ip_id = @ipId; ";
                                    command.ExecuteScalar();
                                }
                            }

                            command.CommandText = "Delete from network where n_id = @networkId; ";
                            command.ExecuteScalar();
                        }
                    }

                    command.CommandText = "Delete from location where l_id = @locationID; ";
                    command.ExecuteScalar();
                }
            }

            command.CommandText = "Delete from customer where c_id = @customerId; ";
            command.ExecuteScalar();

            // Attempt to commit the transaction.
            transaction.Commit();

            return true;
        } 
        catch (Exception ex) {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            try {
                transaction.Rollback();
            } 
            catch (Exception ex2) {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }

            return false;
        }
    }
}

谢谢!

读取错误消息时,您已经具有与该Command对象关联的打开的DataReader

您需要为每个要执行的(嵌套)命令创建一个新的SqlCommand对象。

SqlCommand locationCommand = connection.CreateCommand();
SqlCommand networkCommand = connection.CreateCommand();
SqlCommand ipAddrCommand = connection.CreateCommand();

根据需要将CommandText分配给每个命令对象,然后可以在每个对象上调用ExecuteReader并根据需要进行处理。

对外部和内部命令使用不同的命令实例; 所以本质上:

var innerCommand = ...
innerCommand.CommandText = "Delete from ipaddress where ip_id = @ipId; ";
var ipId = innerCommand.Parameters.Add(...);
while (ipaddressReader.Read()) {
    ipId.Value = ...
    innerCommand.ExecuteNonQuery();
}

(每个命令都类似)

基本上,每个命令实例一次只能执行一次,无论它们是否共享连接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM