连接未关闭。连接的当前状态已打开 [英] Connection was not closed.the connection's current state is open

查看:152
本文介绍了连接未关闭。连接的当前状态已打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在下面运行时出错(即)连接没有关闭,连接的当前状态是打开的。



我有什么试过:



my code is below there is a error while running(i.e) connection was not closed,the connection's current state is open.

What I have tried:

private void button2_Click(object sender, EventArgs e)
        {
            con.Open();
            
            OleDbCommand delcmd = new OleDbCommand();
            //if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count-1)
            if(dataGridView1.SelectedRows.Count > 0 && dataGridView1.SelectedRows[0].Index!=dataGridView1.Rows.Count-1)
            
            {
                delcmd.CommandText = "delete from table123 where Idno=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
               
                delcmd.Connection = con;
                delcmd.ExecuteNonQuery();
                con.close();
                dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                MessageBox.Show("Row Deleted");
                bind();
                clear();
            }
}

推荐答案

连接的关闭嵌入在if条件中,将其移到如果条件为真,它将仅关闭,并且无论条件如何都应关闭连接。



The close for the connection is embedded within an if condition, move it outside of the if as it will only close if the condition is true and you should close the connection regardless of the condition.

private void button2_Click(object sender, EventArgs e)
        {
            //if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count-1)
            if(dataGridView1.SelectedRows.Count > 0 && dataGridView1.SelectedRows[0].Index!=dataGridView1.Rows.Count-1)
            
            {
                using (OleDbCommand delcmd = new OleDbCommand())
                {
                   delcmd.CommandText = "delete from table123 where Idno=@ID";
               
                   delcmd.Connection = con;
                   delcmd.Parameters.Add("@ID", dataGridView1.SelectedRows[0].Cells[0]);

                   con.Open();
                   delcmd.ExecuteNonQuery();
                   con.close();
                }
                dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                MessageBox.Show("Row Deleted");
                bind();
                clear();
            }

}





改进的答案,如果无事可做,无需打开连接,添加了适当的参数化字符串。



Improved answer, no need to open connection if nothing to do, added proper parameterised string.


这篇关于连接未关闭。连接的当前状态已打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆