我该如何解决这些问题 [英] How do I solve these problem

查看:87
本文介绍了我该如何解决这些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

The connection was not closed. The connection's current state is open. 





我的尝试:





What I have tried:

Line 37:                    
Line 38:                    
Line 39:                     conn.Open();
Line 40:                     cmd.ExecuteNonQuery();
Line 41:                     conn.Close();

推荐答案

这意味着您尝试打开的连接是已经打开。

这意味着你正在重复使用连接,并且当你完成连接时,你没有正确地关闭它。



处理此问题的最佳方法是不回收连接,而是在中使用块在需要时创建它们。这样,当它们超出范围时,它们会自动关闭和处置:

What that means is that the connection you are trying to open is already open.
And that means you are reusing a connection, and somewhere you are not closing it properly when you are finished with it.

The best way to deal with this is not to "recycle" connections, but create them when you need them inside a using block. That way, they are Closed and Disposed automatically when they go out of scope:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT Id, description FROM myTable", con))
        {
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["Id"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", id, desc);
                }
            }
        }
    }


这篇关于我该如何解决这些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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