简介微软发布的Data Access Application Block

  为了方便的访问数据,微软自己封装了一个数据访问模块, 即Data Access Application Block. 通过它,我们用来访问数据库的编码量大大减少了. 这样的代码既有效率,又减少了出现错误的几率,其益处是可见的. 下面举两个例子比较一下

1. 使用一般的sql语句进行控件绑定, 常规代码如下:

// Create the connection and sql to be executed
  string  strConnTxt  =   " Server=(local);Database=Northwind;Integrated Security=True; " ;
 
string  strSql  =   " select * from Products where categoryid = 1 "
 
 
// Create and open the connection object
 SqlConnection objConn  =   new  SqlConnection(strConnTxt);
 objConn.Open();
 
 
/ Create the connamd  object
SqlCommand objCmd 
=   new  SqlCommand(strSql, objConn);
objCmd.CommandType 
=  CommandType.Text;

// databind the datagrid by calling the ExecuteReader() method
DataGrid1.DataSource  =  objCmd.ExecuteReader();
DataGrid1.DataBind();

// close the connection
objConn.Close();
如果用微软封装的Data Access Application Block, 其主要是sqlHelper类,代码如下:
// Create the connection string and sql to be executed
string  strSql  =   " select * from products where categoryid = 1 " ;
string  strConnTxt  =   " Server=(local);Database=Northwind;Integrated Security=True; " ;

DataGrid1.DataSource 
=  SqlHelper.ExecuteReader(strConnTxt, CommandType.Text, strSql);
DataGrid1.DataBind();

2. 调用存储过程进行控件绑定
常规代码如下:
// Open a connection to Northwind
SqlConnection objConn  =   new  SqlConnection( " Server=(local);Database=Northwind;Integrated Security=True; " );
 ObjConn.Open();

 
// Create the stored procedure command object
 SqlCommand objCmd  =   new  SqlCommand( " getProductsCategory " , objConn);
 objCmd.CommandType 
=  CommandType.StoredProcedure;
 
 
// create the parameter object for the stored procedure parameter
objCmd.Parameter.Add( " @CategoryID " , SqlDbType.Int);
objCmd.Parameter[
" @CategoryID " ].Value  =   1 ;

// create our DataAdapter and DataSet objects
SqlDataAdapter objDA  =   new  SqlDataAdapter(objCmd);
DataSet objDS 
=   new  DataSet( " Category_Results " );

// fill the dataset
objDA.Fill(objDS);

// databind the datagrid
DataGrid1.DataSource  =  objDS;
DataGrid1.DataBind();

// close connection
objConn.Close();

如果用微软封装的Data Access Application Block,其主要是sqlHelper类,代码如下:
string  strConn  =   " Server=(local);Database=Northwind;Integrated Security=True; " ;
DataSet objDS 
=  SqlHelper.ExecuteDataset(strConn, CommandType.StoredProcedure,  " getProductsByCategory " new  SqlParameter( " @CategoryID " 1 ));

DataGrid1.DataSource 
=  objDS;
DataGrid1.DataBind();

Data Access Application Block, 有其封装的源代码和帮助文件,我们也可以根据项目需求做一下改动再编译成dll引入项目,以给项目开发带来便利. 下载地址如下:
http://download.microsoft.com/download/VisualStudioNET/daabref/RTM/NT5/EN-US/DataAccessApplicationBlock.msi
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值