【问题标题】:Connection was not closed. Connection's current state is open连接未关闭。连接的当前状态是打开
【发布时间】:2015-06-05 00:02:01
【问题描述】:

它给出了错误连接没有关闭。连接的当前状态是打开的。 请帮忙写代码。

  private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
        try
        {
            con.Open();

            SqlCommand cmd = new SqlCommand("Select * FROM [plan] where plantype='" + comboBox1.Text + "'", con);

            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                string amount = dr.GetString(1);
                textBox5.Text = amount;

            }
            con.Close();
        }

        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

}

【问题讨论】:

  • 错误出现在哪一行?
  • 它没有显示任何错误行,我尝试将 con.Close();在 finally 块内,我仍然得到同样的错误。
  • 去掉try/catch看看哪里出错了,或者干脆一步一步来
  • 当你在调试器中运行代码时,会出现一行代码。
  • 删除try catch块后仍然没有显示任何错误行。真的很奇怪

标签: c# connection


【解决方案1】:

您应该使用using 块来帮助管理您的对象。

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string connStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
        string cmdText = "Select * FROM [plan] where plantype=@planType";

        using (SqlConnection con = new SqlConnection(connStr))
        using (SqlCommand cmd = con.CreateCommand())
        {
            con.Open();
            cmd.CommandText = cmdText;
            cmd.Parameters.AddWithValue("@planType", comboBox1.Text);

            var reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

            if (reader.Read())
            {
                string amount = reader.GetString(1);
                textbox5.Text = amount;
            }
        }
    }

还要注意使用参数化查询来避免 SQL 注入攻击。由于您可能只希望返回一个值,因此您应该在查询中指定列的名称并使用ExecuteScalar 而不是阅读器和while 循环。另一种选择是使用CommandBehavior.SingleRow 作为命令的参数,它告诉命令只返回单行结果。

你这里还有一个跨线程问题,可以通过一些调用来解决。

string amount = string.Empty;
if (reader.Read())
{
    amount = reader.GetString(1);
}
if (this.InvokeRequired)
    this.Invoke((MethodInvoker) delegate { textbox5.Text = amount; });
else
    textbox5.Text = amount;

另外需要注意的是,给你的控件起有意义的名字。它比combobox1 或tbx_PlanAmount 比textbox5 更容易调试或理解名为cbx_PlanType 的控件。

【讨论】:

  • 感谢您指导我完成此操作,但我仍然遇到同样的错误。我对此很陌生。
  • 您是否在其他未关闭的地方使用 SQL-Server 连接?
  • 谢谢我现在解决了。它在另一个班级开放。
【解决方案2】:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
    try
    {
        con.Open();

        SqlCommand cmd = new SqlCommand("Select * FROM [plan] where plantype='" + comboBox1.Text + "'", con);

        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            string amount = dr.GetString(1);
            textBox5.Text = amount;

        }
        // check if connection is open
        if (con.State == 1)
            con.Close();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        // check if connection is open
        if (con.State == 1)
            con.Close();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多