Will ExecuteReader(CommandBehavior.CloseConnection) always close connection?

后端 未结 5 976
栀梦
栀梦 2021-01-11 14:27

Is it safe to write this helper method like this? Will it always close the connection? I understend if all goes well, it will, but will ExecuteReader close the connection ev

5条回答
  •  无人及你
    2021-01-11 15:06

    I know the question is related to closing the connection which will be the case; however, the connection won't be disposed. To dispose the connection itself, you need to enclose it a using block as well:

    using (DBConnection conn = new ...)
    {
        using (DbCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = commandText;
            conn.Open();
            using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                foreach (DbDataRecord record in reader) { yield return record; }
            }
        }
    }
    

    UPDATE I thought this was an interesting question so I wrote the following test:

    string connString = @"Data Source=.\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True;";
    SqlConnection conn = new SqlConnection(connString);
    
    try
    {
    using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = "select  from MSdbms"; 
            conn.Open();
            Console.WriteLine(conn.State);
            using (IDataReader reader = cmd.ExecuteReader())//Will throw an exception - Invalid SQL syntax -see setting CommandText above
            {
                Console.WriteLine("here");
            }
        }
    }
    catch(Exception ex)
    {  Console.WriteLine(conn.State); } //prints Open
    

    If the line using (IDataReader reader = cmd.ExecuteReader()) is changed to: using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) then it prints Closed. Something to keep in mind.

提交回复
热议问题