教你使用DataAdapter優(yōu)化ADO.NET連接池
經(jīng)過長(zhǎng)時(shí)間學(xué)習(xí)ADO.NET連接池,于是和大家分享一下,看完本文你肯定有不少收獲,希望本文能教會(huì)你更多東西。用于ODBC的SQL Server、OLE DB和.NET框架數(shù)據(jù)提供程序隱式緩沖連接。通過在連接字符串中指定不同的屬性值,可以控制ADO.NET連接池的行為。
#T#DataAdapter 的Fill和Update方法在連接關(guān)閉的情況下自動(dòng)打開為相關(guān)命令屬性指定的連接。如果Fill或Update方法打開了連接,F(xiàn)ill或Update 將在操作完成的時(shí)候關(guān)閉它。為了獲得***性能,僅在需要時(shí)將與數(shù)據(jù)庫的連接保持為打開。同時(shí),減少打開和關(guān)閉多操作連接的次數(shù)。如果只執(zhí)行單個(gè)的Fill或Update方法調(diào)用,建議允許Fill或Update方法隱式打開和關(guān)閉連接。如果對(duì)Fill和Update調(diào)用有很多,建議顯式打開連接,調(diào)用Fill和Update,然后顯式關(guān)閉連接。另外,當(dāng)執(zhí)行事務(wù)時(shí),顯式地在開始事務(wù)之前打開連接,并在提交之后關(guān)閉連接。例如:
- 'Visual Basic
 - Public Sub RunSqlTransaction(da As SqlDataAdapter, myConnection As SqlConnection, ds As DataSet)
 - myConnection.Open()
 - Dim myTrans As SqlTransaction = myConnection.BeginTransaction()
 - myCommand.Transaction = myTrans
 - Try
 - da.Update(ds)
 - myTrans.Commit()
 - Console.WriteLine("Update successful.")
 - Catch e As Exception
 - Try
 - myTrans.Rollback()
 - Catch ex As SqlException
 - If Not myTrans.Connection Is Nothing Then
 - Console.WriteLine("An exception of type " & ex.GetType().ToString() & " was encountered while attempting to roll back the transaction.")
 - End If
 - End Try
 - Console.WriteLine("An exception of type " & e.GetType().ToString() & " was encountered.")
 - Console.WriteLine("Update failed.")
 - End Try
 - myConnection.Close()
 - End Sub
 - //C#
 - public void RunSqlTransaction(SqlDataAdapter da, SqlConnection myConnection, DataSet ds)
 - {
 - myConnection.Open();
 - SqlTransaction myTrans = myConnection.BeginTransaction();
 - myCommand.Transaction = myTrans;
 - try
 - {
 - da.Update(ds);
 - myCommand.Transaction.Commit();
 - Console.WriteLine("Update successful.");
 - }
 - catch(Exception e)
 - {
 - try
 - {
 - myTrans.Rollback();
 - }
 - catch (SqlException ex)
 - {
 - if (myTrans.Connection != null)
 - {
 - Console.WriteLine("An exception of type " + ex.GetType() +" was encountered while attempting to roll back the transaction.");
 - }
 - }
 - Console.WriteLine(e.ToString());
 - Console.WriteLine("Update failed.");
 - }
 - myConnection.Close();
 















 
 
 
 
 
 
 