select * from customers where ((LastName=@LastName) or (LastName IS NULL and @LastName IS NULL))
上面语句检查了列是否为空和参数是否为空。
VII.传递null参数值
当你在命令中传递null参数值给数据库时,你不能使用null(Nothing在vb中),应该使用DBNull.Value。举例:
‘vb
Dim param As SqlParameter = New SqlParameter(“@Name”,SqlDbType.NVarChar,20)
param.Value = DBNull.Value
‘C#
SqlParameter param = new SqlParameter(“@Name”,SqlDbType.NVarChar,20);
param.Value = DBNull.Value;
VIII.使用事务处理
ADO.NET中的事务处理模型已经改变,在ADO中,一旦StartTransaction被调用,任何事务下的更新都被认为是事务的一部分。然而,在ADO.NET中,当Connection.BeginTransaction被调用,返回一个命令关联的事务对象(事务属性是由命令的事务属性指定的)。这样保证让你在一个Connection中执行多个事务。如果命令的Command.Transaction属性与开始的事务不一致,命令就不会完成并抛出错误。
IX.使用Connections
高效率的应用程序应该使用最少的时间与数据库建立连接,比如使用Connection Pooling等。下面将介绍如何使用ADO.NET建立高效率应用的一些数据库方面的技巧。
①Connection Pooling
在SQL Server、OLE DB和.NET框架结构中的Data Provider中,都提供了隐式的连接池连接支持。你可以在ConnectionString中指定不同的参数值控制连接池的行为。比如下面的例子使OLE DB的连接池无效并自动地进行事务处理:
Provider=SQLOLEDB;OLE DB Services=-4;Data Source=localhost;Integrated Security=SSPI;
在SQL Server.NET Data Provider中提供了以下参数设置控制连接池的行为:Connection Lifttime、Connection Reset、Enlist、Max Pool Size、Min Pool Size和Pooling。
②使用DataAdapter最优化连接
使用DataAdpater的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
上一页 [1] [2] [3] [4] [5] 下一页 [C语言系列]NET 中C#的switch语句的语法 [系统软件]托拽Explore中的文件到VB.net的窗口 [系统软件]Boost库在XP+Visual C++.net中的安装 [常用软件]新配色面板:Paint.Net3.0RC1官方下载 [常用软件]用内建的“Net Meeting”聊天 [VB.NET程序]Henry的VB.NET之旅(三)—共享成员 [VB.NET程序]Henry的VB.NET之旅(二)—构造与析构 [VB.NET程序]Henry的VB.NET之旅(一)—失踪的窗体 [VB.NET程序]在托盘上显示Balloon Tooltip(VB.NET) [VB.NET程序]Henry手记-VB.NET中动态加载Treeview节点(二)
|