【问题标题】:While more query executing, i got "Not allowed to change the 'ConnectionString' property."在执行更多查询时,我得到“不允许更改 'ConnectionString' 属性。”
【发布时间】:2016-12-28 11:52:37
【问题描述】:
class CommonConnection
{
    public class dStructure
    {
        public static string ConnectionString = "";
    }

    public SqlConnection Conn;
    #region "Connection Procedures"
    public string ConnectionString
    {
        get
        {
            string sConn = string.Empty;
            sConn = @"Server=ServerName;Initial Catalog=Database;User ID=userid;Password=password;";
            dStructure.ConnectionString = sConn;
            return dStructure.ConnectionString;

        }
    }

    public void cnOpen()
    {
        try
        {
            if (Conn == null)
            {
                Conn = new System.Data.SqlClient.SqlConnection();
            }
            if (Conn.State == ConnectionState.Open)
            {
                Conn.Close();
            }
            Conn.ConnectionString = ConnectionString;
            Conn.Open();
        }
        catch (SqlException e)
        {
            SqlConnection.ClearAllPools();
            throw e;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void cnClose()
    {
        try
        {
            if ((Conn != null))
            {
                if (Conn.State == ConnectionState.Open)
                {
                    Conn.Close();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            Conn = null;
        }
    }
    #endregion

    public int ExecuteQuery(string strQuery, Int16 TimeOut = 30)
    {
        int RecordsAffected;
        SqlCommand cmd;
        try
        {
            cnOpen();
            cmd = new SqlCommand(strQuery, Conn);
            cmd.CommandTimeout = TimeOut;
            RecordsAffected = cmd.ExecuteNonQuery();

            return RecordsAffected;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            cnClose();
            cmd = null;
        }
    }        
}

// 尝试了另一个选项,如下所示,

    public int ExecuteQuery(string strQuery, short TimeOut = 10)
    {
        SqlConnection NewConn = new SqlConnection();
        try
        {
            if (NewConn == null)
            {
                NewConn = new System.Data.SqlClient.SqlConnection();
            }
            if (NewConn.State == ConnectionState.Open)
            {
                NewConn.Close();
            }
            NewConn.ConnectionString = "Server=ServerName;Initial Catalog=Database;User ID=userid;Password=password;";
            NewConn.Open();

            return new SqlCommand(strQuery, NewConn)
            {
                CommandTimeout = ((int)TimeOut)
            }.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            NewConn.Close();
        }
    }

但仍然遇到同样的问题。 它的桌面应用程序,多线程。但是,虽然对此有更多的查询负载,但我却不允许更改“ConnectionString”属性。连接的当前状态是打开的。 请注意,不是每次我都遇到这个问题,只有在执行更多查询时。

// 更新 2 根据另一个问题中的建议,我尝试使用以下代码,但问题仍然存在。

    public int ExecuteQuery(string strQuery, short TimeOut = 10)
    {
        int executeReader = 0;
        try
        {
            using (SqlConnection connection = new SqlConnection(@"Server=Server;Initial Catalog=DB;User ID=id;Password=Password;"))
            {
                try
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand(strQuery, connection);
                    command.CommandType = CommandType.Text;
                    command.CommandTimeout = TimeOut;
                    executeReader = command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return executeReader;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

正如那里所建议的,使用命令使用默认 IDisposable,因此无需关闭连接。

【问题讨论】:

  • 你试过简单的new SqlConnection("... connection string ..."); 吗?
  • 另外,指出您得到异常的确切位置,因为允许更改 SqlConnection 对象的连接字符串属性。
  • 而且代码是不必要的复杂。您首先构造一个新的 SqlConnection 对象,然后输入一个 try/catch,在其中检查变量是否为空,即您刚刚将对象引用放入的那个,所以它不可能。然后检查连接是否打开,但由于它刚刚构建,它将被关闭。然后设置连接字符串并打开它。能否请您简化代码并指出您获得异常的确切位置?
  • @LasseV.Karlsen 他的代码对于一个或两个查询运行良好我也检查过。如果他尝试执行多个查询,则会引发异常。我试图给出答案,但他说这也给出了例外。请也检查我的答案,让我们知道我的答案中有什么不适合他的问题。
  • 不起作用的是他在多线程应用程序中执行此操作。他不应该跨多个线程使用同一个连接对象。

标签: c# sql sql-server sqlconnection sqlcommand


【解决方案1】:

试试这个

类:

 public class CommonConnection
{
    String constr = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
    public CommonConnection()
    {

        //
        // TODO: Add constructor logic here
        //
    }
    //Insert,Update,Delete....
    public int ExecuteNonQuery1(string str)
    {
        //String constr = System.Configuration.ConfigurationManager.ConnectionStrings["CommonConnection"].ConnectionString;

        SqlConnection con = new SqlConnection(constr);

        SqlCommand cmd = new SqlCommand(str, con);


        int result = 0;

        try
        {

            con.Open();
            result = cmd.ExecuteNonQuery();


            con.Close();
        }
        catch (Exception ex)
        {
            result = -1;
            try
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            catch (Exception ex2)
            {
                // ErrHandler.WriteError(ex2.ToString());
            }
            // ErrHandler.WriteError(ex.ToString());
        }

        return result;

    }
}

ASPX.CS:

        SortedList s1 = new SortedList();
        s1.Add("@mode", "Update");
        s1.Add("@cid", ViewState["CategoryId"]);
        int a = sp.ExecuteNonQuerySP1("SP_Name", s1);
        if (a > 0)
        {
        }

【讨论】:

  • 可能无法工作,因为与我的代码相比没有重大变化。虽然会在检查后更新你
【解决方案2】:

在您的两个代码 DEMO 中都是 catch.. 让我们检查一下。

public void cnOpen()
        {
            try
            {
                if (Conn == null)
                {
                    Conn = new System.Data.SqlClient.SqlConnection();
                }
                if (Conn.State == ConnectionState.Open)
                {
                    Conn.Close();
                }
                Conn.ConnectionString = ConnectionString;
                Conn.Open();
            }`

假设if conn == null 然后它将进入块并创建新连接,一切都很好。但是如果条件为假怎么办,那么它不会创建新的sqlConnection 实例,它会移动到第二个如果条件

 if (Conn.State == ConnectionState.Open)
            {
                Conn.Close();
            }

既然你告诉了更多查询何时执行,所以连接状态也可能是除了打开之外的任何状态,比如连接、获取、断开等,所以如果有的话,这个 if 条件将是 false其中除了ConnectionState.Open 之外发生,并且您现有的连接不会关闭,并且它会进一步转到它将遇到的下一行

Conn.ConnectionString = ConnectionString;

如果您的连接没有关闭,那么它将尝试更改现有连接的(SqlConnection 实例)连接字符串。如果实例未处置,则无法更改。因此它将引发异常。

EDIT 尝试做这样的事情并从这段代码中删除Conn.open()

    if (Conn.State == ConnectionState.Open)
            {
                Conn.Close();
            }
    if (Conn == null)
                {
                    Conn = new System.Data.SqlClient.SqlConnection();
                    Conn.ConnectionString = ConnectionString;


                }

还有一件事你需要在 public int ExecuteQuery(string strQuery, Int16 TimeOut = 30) in 方法中更新。把这行Conn.Open();放在cmd.CommandTimeout = TimeOut之后;

public int ExecuteQuery(string strQuery, Int16 TimeOut = 30)
    {
        int RecordsAffected;
        SqlCommand cmd;
        try
        {   
            cnOpen(); 
            cmd = new SqlCommand(strQuery, Conn);
            cmd.CommandTimeout = TimeOut;
            Conn.Open();    //Add this here
            RecordsAffected = cmd.ExecuteNonQuery();

            return RecordsAffected;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            cnClose();
            cmd = null;
        }
    }        
}

【讨论】:

  • 写cnOpen();在 NewConn.Close() 之后的第二个 if 块;并检查现在是否可以!
  • 现在我得到“ConnectionString 属性尚未初始化。”错误。所以我修改如下, if (string.IsNullOrEmpty(NewConn.ConnectionString)) NewConn.ConnectionString = Connection string here"; 之后我得到以下错误,1) 不允许更改 'ConnectionString' 属性。连接的当前状态是连接中。2) SelectCommand.Connection 属性尚未初始化。3) ExecuteReader 需要一个打开且可用的连接。连接的当前状态是打开的。请帮帮我
  • 更新了我的帖子,请查看并告诉我。
  • 不工作。也尝试了下面的代码,但没有运气。使用 (SqlConnection 连接 = 新 SqlConnection(ConnectionString)) { connection.Open(); SqlCommand command = new SqlCommand(strQuery, connection); command.CommandType = CommandType.Text; command.CommandTimeout = 超时; executeReader = command.ExecuteNonQuery();在这里使用了 try catch 但在评论空间问题中没有提及。
  • 你不能先使用 connection.open() 总是在 excecuteReader 之前使用它。并告诉我更新后的代码有什么错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多