正 文

ADO.NET实用经验无保留曝光


www.7dspace.com  更新日期:2005-11-14 8:03:30  七度空间


  用DataAdapter优化连接

  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();
}

  始终关闭Connection和DataReader

  完成对Connection或DataReader对象的使用后,总是显式地关闭它们。尽管垃圾回收最终会清除对象并因此释放连接和其他托管资源,但垃圾回收仅在需要时执行。因此,确保任何宝贵的资源被显式释放仍然是您的责任。并且,没有显式关闭的Connections可能不会返回到池中。例如,一个超出作用范围却没有显式关闭的连接,只有当连接池大小达到最大并且连接仍然有效时,才会被返回到连接池中。

  注不要在类的Finalize方法中对Connection、DataReader或任何其他托管对象调用Close或Dispose。最后完成的时候,仅释放类自己直接拥有的非托管资源。如果类没有任何非托管资源,就不要在类定义中包含Finalize方法。

10页,页码:[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 

上一篇:20种看ASP程序源码的方法及工具
下一篇:美术基础图解:冷暖色与对比色
作者:  来源:ASPCOOL ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐