经过长时间学习ADO.NET连接池,于是和大家分享一下,看完本文你肯定有不少收获,希望本文能教会你更多东西。用于ODBC的SQL Server、OLE DB和.NET框架数据提供程序隐式缓冲连接。通过在连接字符串中指定不同的属性值,可以控制ADO.NET连接池的行为。
#T#DataAdapter 的Fill和Update方法在连接关闭的情况下自动打开为相关命令属性指定的连接。如果Fill或Update方法打开了连接,Fill或Update 将在操作完成的时候关闭它。为了获得***性能,仅在需要时将与数据库的连接保持为打开。同时,减少打开和关闭多操作连接的次数。如果只执行单个的Fill或Update方法调用,建议允许Fill或Update方法隐式打开和关闭连接。如果对Fill和Update调用有很多,建议显式打开连接,调用Fill和Update,然后显式关闭连接。另外,当执行事务时,显式地在开始事务之前打开连接,并在提交之后关闭连接。例如:
- '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();