我只想就使用SqlConnection对象的正确用法或正确设计发表意见.以下2中哪一个是最佳用途:
一个数据提供程序类,其方法(每个方法)包含SqlConnection对象(并在完成时处理).喜欢:
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...
}
}
Run Code Online (Sandbox Code Playgroud)
要么
SqlConnection connection; // initialized in constructor
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
}
Run Code Online (Sandbox Code Playgroud)
还是有比这更好的方法?我有一个专注的Web爬虫类型的应用程序,该应用程序将同时爬网50个或多个网站(多线程)与爬虫对象中包含的每个网站,每个爬虫对象都有一个数据提供程序类的实例(上图).
将合并实际的数据库连接.只要您的所有SqlConnection实例都使用相同的连接字符串,它们就会真正使用相同的连接.
我发现创建连接实例,使用它,然后处理它(在一个using块中)更清洁.这样,如果代码需要更改为使用不同的连接字符串,使用事务或其他任何内容,那么您就可以在此处进行所有更改.