System.InvalidOperationException:连接未关闭。连接的当前速率是打开的,

Posted

技术标签:

【中文标题】System.InvalidOperationException:连接未关闭。连接的当前速率是打开的,【英文标题】:System.InvalidOperationException: The connection was not closed. The connection;s current srate is open, 【发布时间】:2021-12-31 20:24:10 【问题描述】:

软件未记录连接正在连接到 SQL 数据库,但未登录。请查看代码并帮助我提前谢谢

错误:

System.InvalidOPerationException:连接未关闭。连接的当前状态在 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource'1 retry) 的 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource'1 retry) 的 System.Data.ProvideBase.DBConnectionInternal.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskComletionsource'1 retry, DbConnectionOPtions userOPtions) 处打开。 Data.SqlClient.SqlConnection.TryOPenTaskCompletionSource'1 retry) at System.Data.Sqlclient.SqlConnection.OPen() at Login.LoginForm.Login() in D:\Downloads\Compressed\SchoolManaementSystem\SchoolManagementSystem\Login'Forms\Login.cs :第 67 行

public LoginForm()

    InitializeComponent();
    connection = new SqlConnection(ConfigurationManager.ConnectionStrings["CS"].ConnectionString);


#region Methods
//Method For Login Form
public void LoginTeacher()

    using (SqlConnection cnn = new SqlConnection(connectionString))
    
        try
        
            command = new SqlCommand("TeacherLogin", connection);
            command.CommandType = CommandType.StoredProcedure;
            connection.Open();
            command.Parameters.AddWithValue("@username", Txt_User.Text);
            command.Parameters.AddWithValue("@password", Txt_Pass.Text);

            SqlDataReader dataReader = command.ExecuteReader();

            if (dataReader.Read())
            
                TeacherDash teacherDash = new TeacherDash();
                this.Hide();
                teacherDash.lblusertype.Text = dataReader[1] + " " + dataReader[2].ToString();
                teacherDash.ShowDialog();
                this.Close();
            

        
        catch (Exception ex)
        
            MessageBox.Show(ex.ToString());
        
        finally
        
            cnn.Close();
        
    


public void Login()

    using (SqlConnection cnn = new SqlConnection(connectionString))
    
        try
        
            command = new SqlCommand("SP_USER_LOGIN", connection);
            command.CommandType = CommandType.StoredProcedure;
            connection.Open();
            command.Parameters.AddWithValue("@user", Txt_User.Text);
            command.Parameters.AddWithValue("@pass", Txt_Pass.Text);

            SqlDataReader dataReader = command.ExecuteReader();

            if (dataReader.Read())
            
                LoginTeacher();
                if (dataReader[10].Equals("Admin"))
                

                    AdminDash adminDash = new AdminDash();
                    this.Hide();
                    adminDash.lblusertype.Text = dataReader[1] + " " + dataReader[2].ToString();
                    adminDash.ShowDialog();

                    this.Close();
                
                else if (dataReader[10].Equals("Teacher"))
                
                    TeacherDash teacherDash = new TeacherDash();
                    this.Hide();
                    teacherDash.lblusertype.Text = dataReader[1] + " " + dataReader[2].ToString();
                    teacherDash.ShowDialog();
                    this.Close();
                
                else if (dataReader[10].Equals("Accounts"))
                
                    AccountsDash accountsDash = new AccountsDash();
                    this.Hide();
                    accountsDash.lblusertype.Text = dataReader[1] + " " + dataReader[2].ToString();
                    accountsDash.ShowDialog();

                    this.Close();
                
                else if (dataReader[10].Equals("Addmission"))
                
                    AdmissionDash admissionDash = new AdmissionDash();
                    this.Hide();
                    admissionDash.lblusertype.Text = dataReader[1] + " " + dataReader[2].ToString();
                    admissionDash.ShowDialog();
                    this.Close();
                
            
            else if (Txt_User.Text.Trim() == string.Empty & Txt_Pass.Text.Trim() == string.Empty)
            
                MessageBox.Show("UserName And Password Fileds Empty", "Blank Field", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
            else if (Txt_User.Text.Trim() == string.Empty)
            
                MessageBox.Show("Please Enter UserName", "UserName Blank", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            else if (Txt_Pass.Text.Trim() == string.Empty)
            
                MessageBox.Show("Please Enter Password", "Password Blank", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            else
            
                MessageBox.Show("Invalid UserName or Password", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
        
        catch (Exception ex)
        
            MessageBox.Show(ex.ToString());
        
        finally
        
            cnn.Close();
        
    

        

#endregion

private void Btn_Login_Click(object sender, EventArgs e)

    LoginTeacher();
    Login();


private void pictureBox4_Click(object sender, EventArgs e)

    this.Close();


enter image description here

【问题讨论】:

您在每个方法中都创建了新的连接对象,但实际上您是在使用全局connection 变量。然后它将在第一次调用某些东西时打开,而当您再次尝试打开它时,下一次调用将失败。 【参考方案1】:

不要使用全局 connection 变量。

确保连接始终关闭,请在using 块内打开连接,如以下代码片段所示。

这样做可确保在代码退出块时自动关闭连接。

using (SqlConnection connection = new SqlConnection(connectionString))
    
        connection.Open();
        // Do work here; connection closed on following line.
    

可以参考官方documentation。

【讨论】:

对您有帮助吗?如果您不介意,可以点击“✔”将我的回复标记为已接受答案。它还将帮助其他人解决类似的问题。

以上是关于System.InvalidOperationException:连接未关闭。连接的当前速率是打开的,的主要内容,如果未能解决你的问题,请参考以下文章

视图中出现 InvalidOperationException.Collection 被修改错误