Will ExecuteReader(CommandBehavior.CloseConnection) always close connection?

后端 未结 5 938
栀梦
栀梦 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:21

    Yes even if it throws an exception it will close the connection. If you do not specify CommandBehavior.CloseConnection and you close the connection, your calling code cannot access the contents of the reader.

    Also from MSDN:

    When the command is executed, the associated Connection object is closed when the associated DataReader object is closed.

    You should ensure that the reader is closed when you are done with it. The nice thing about all of this is you've got it wrapped around a using statement and you aren't using try/catch/finally in this case the reader will be closed which then will close the database connection.

提交回复
热议问题