2017-07-02 29 views
0

我想知道是否需要在每個存儲庫函數中使用using語句以確保在每批數據庫調用之後關閉連接。確保在調用每個回購函數後總是關閉SQL數據庫連接

例如:我想在某些存儲庫函數內多次調用connection.query或connection.execute。如果我不使用using語句,我的連接何時關閉?目標是儘可能提高Web開發的效率。

BaseRepository

public static string ConnectionString => @"Server=.;Database=applicationDb;User ID=sa;Password=Password12!"; 
protected SqlConnection _connection; 
protected SqlConnection connection => _connection ?? (_connection = GetOpenConnection()); 

public static SqlConnection GetOpenConnection(bool mars = false) 
{ 
    var cs = ConnectionString; 
    if (mars) 
    { 
     var scsb = new SqlConnectionStringBuilder(cs) 
     { 
      MultipleActiveResultSets = true 
     }; 
     cs = scsb.ConnectionString; 
    } 
    var connection = new SqlConnection(cs); 
    connection.Open(); 
    return connection; 
} 

public SqlConnection GetClosedConnection() 
{ 
    var conn = new SqlConnection(ConnectionString); 
    if (conn.State != ConnectionState.Closed) throw new InvalidOperationException("should be closed!"); 
    return conn; 
} 

public void Dispose() 
{ 
    _connection?.Dispose(); 
} 

CustomerRepository:BaseRepository

隨着BaseRepository設置事情是這樣的。有以下任何區別:

public IEnumerable<Customer> GetCustomers() 
{ 
    using (connection) 
    { 
     StringBuilder sql = new StringBuilder(); 
     sql.AppendLine("SELECT Id, Name, Email "); 
     sql.AppendLine("FROM Customer;"); 

     StringBuilder deleteSql = new StringBuilder(); 
     deleteSql = new StringBuilder(); 
     deleteSql.AppendLine("DELETE FROM Xyz "); 
     deleteSql.AppendLine("FROM CustomerId = @CustomerId;"); 
     connection.Execute(deleteSql.ToString(), new { CustomerId = 5 }); 

     return connection.Query<Customer>(sql.ToString()).ToList(); 
    } 
} 

或不使用:

public IEnumerable<Customer> GetCustomers() 
{ 
     StringBuilder sql = new StringBuilder(); 
     sql.AppendLine("SELECT Id, Name, Email "); 
     sql.AppendLine("FROM Customer;"); 

     StringBuilder deleteSql = new StringBuilder(); 
     deleteSql = new StringBuilder(); 
     deleteSql.AppendLine("DELETE FROM Xyz "); 
     deleteSql.AppendLine("FROM CustomerId = @CustomerId;"); 
     connection.Execute(deleteSql.ToString(), new { CustomerId = 5 }); 

     return connection.Query<Customer>(sql.ToString()).ToList(); 
} 

回答

1

你需要(如果你想處理異常或try...catch)包裹在using聲明您的來電,並將關閉它並自動處理它。

+0

這正是我想弄明白的。因此,如果我沒有爲每個函數使用語句,BaseRepository的設置方式就是這樣,連接永遠不會關閉正確嗎?我在想也許這不是一件壞事,如果BaseRepository總是檢查一個已經存在的連接是否使用它,那麼爲什麼不長時間保持相同的連接呢?否則打開另一個連接。 –

+1

您無需擔心經常打開和關閉連接。實際上,我們鼓勵您在完成後立即關閉連接。這不會真正關閉連接。它會將它返回到連接池,並且下一次嘗試打開新連接(在很短的時間內)時,實際上會從池中獲得連接。 –

2

我這裏的建議是使用using聲明,因爲using聲明的目的是當控件將達到使用結束時它將配置該使用塊的對象並釋放內存。它的目的不僅在於自動連接關閉,基本上它會配置連接對象,明顯連接也因此關閉。