passing DB Connection object to methods

前端 未结 9 1749
抹茶落季
抹茶落季 2020-12-25 13:29

Was wondering if it is recomended to pass a database connection object around(to other modules) or let the method (in the other module) take care of setting it up. I am lea

9条回答
  •  情歌与酒
    2020-12-25 14:02

    I would suggest that you distinguish between the connection object and its state (open, closed).

    You can have a single method (or property) that reads the connection string from web.config. Using the same version of the connection string every time ensures that you will benefit from connection pooling.

    Call that method when you need to open a connection. At the very last moment, after setting up all of the SqlCommand properties, open the connection, use it, and then close it. In C#, you can use the using statement to make sure the connection is closed. If not, be sure to close the connection in a finally block.

提交回复
热议问题