开发者

Proper Usage of SqlConnection in .NET

I just want an opinion on the proper usage or a proper design with regards to using SqlConnection object. Which of the 2 below is the best use:

A data provider class whose methods (each of them) contain SqlConnection object (and disposed when done). Like:

IList<Employee> GetAllEmployees() 
{ 
  using (SqlConnection connection = new SqlConnection(this.connectionString)) { 
  // Code goes here... 
  } 
} 

Employee GetEmployee(int id) 
{ 
  using (SqlConnection connection = new SqlConnection(this.connectionString)) { 
  // Code goes here... 
  } 
}   

or

SqlConnection connection; // initialized in constru开发者_StackOverflowctor 
IList<Employee> GetAllEmployees() 
{ 
  this.TryOpenConnection(); // tries to open member SqlConnection instance 
  // Code goes here... 
  this.CloseConnection(); 
  // return 
} 

Employee GetEmployee(int id) 
{ 
  this.TryOpenConnection(); // tries to open member SqlConnection instance 
  // Code goes here... 
  this.CloseConnection(); 
  // return 
}

Or is there a better approach than this? I have a focused web crawler type of application and this application will crawl 50 or more websites simultaneously (multithreaded) with each website contained in a crawler object and each crawler object has an instance of a data provider class (above).


The actual database connections will be pooled. As long as all of your SqlConnection instances use the same connection string, they'll all really use the same connection.

I find it cleaner to create the connection instance, use it, then dispose it (in a using block). That way, if the code needs to change to use a different connection string, to use a transaction, or whatever, you have all you need to make the change available right there.


Maybe not really related, but the only time I'd separate any connection object to the class instance level is when I want to create a clear separation of concern to what each method is doing... Perhaps it's too long and need to be refactored into several pieces and each of them need to operate on the same connection as part of a transaction.

I.e.

Create a connection
Start transaction
Call a subroutine to update an order header (passing along the connection or get it from the instance)
Call a subroutine to update all order details (passing along the conneciton or get it from the instance)
End transaction
Close connection

Otherwise, I'd pretty much stick to option 1. W/ connection pooling it's basically won't cost you anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜