'ExecuteReader requires an open and available Connection. The connection's current state is open'

谁都会走 提交于 2019-12-04 05:24:01
Jesse C. Slicer

In addition to leppie's answer, you should also be Dispose()ing of any IDisposable types:

        try
        {
            Database.Open(); // Custom class that has our connection string hard coded.

            string query = "SELECT * FROM table"; // (dummy query)

            using (SqlCommand command = new SqlCommand(query, Database.Conn))
            using (SqlDataReader reader = command.ExecuteReader(CommandBehaviour.CloseConnection))
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        // Do something with the data.
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }

It looks to me that Database is a type and not an instance.

You are running into multithreading issues now.

You have 2 options:

  • Apply the [ThreadStatic] to the field containing the connection object created by Database.Open()

or

  • Make Database.Open() return a fresh instance of the connection object and use that when constructing the command
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!