簡體   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