SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot
    Join Date
    Jan 2010
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question invalid operation exception

    i have a question in invalid operation exception. it says that " ExecuteReader Connection is closed and must be open
    Code ASP:
    SqlConnection conn = new SqlConnection("Server=localhost\\SqlExpress;" +
    "Database=db;Integrated Security=True");
                SqlCommand comm = new SqlCommand("SELECT EmpID, Name FROM Employee", conn);
     
                SqlDataReader reader = comm.ExecuteReader();

  2. #2
    SitePoint Zealot
    Join Date
    Jan 2010
    Posts
    132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok,the problem solved

    add this line before reader

    comm.Connection.Open();

    PHP Code:
    SqlConnection conn = new SqlConnection("Server=localhost\\SqlExpress;" +
    "Database=db;Integrated Security=True");
                
    SqlCommand comm = new SqlCommand("SELECT EmpID, Name FROM Employee"conn);
                
    comm.Connection.Open();
                
    SqlDataReader reader comm.ExecuteReader(); 

  3. #3
    SitePoint Author silver trophybronze trophy
    wwb_99's Avatar
    Join Date
    May 2003
    Location
    Washington, DC
    Posts
    10,652
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    Make sure you close that connection and that reader. Best bet would be to wrap both in a using block:

    Code:
    using (var conn = new SqlConnection(cstring))
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText="SELECT foo FROM bar";
        conn.Open();
        using (var r = cmd.ExecuteReader()){
            // do stuff
            r.Close();
        }
        conn.Close();
    }

  4. #4
    SitePoint Wizard webcosmo's Avatar
    Join Date
    Oct 2007
    Location
    Boston, MA
    Posts
    1,480
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    i like to add, if you would use the using you wont need to explicitly close the connection, .net would do that for you.

  5. #5
    SitePoint Author silver trophybronze trophy
    wwb_99's Avatar
    Join Date
    May 2003
    Location
    Washington, DC
    Posts
    10,652
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    True, but I'd generally contend that it is better to have explicit intent rather than rely upon implicit behavior.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •