为了方便的访问数据,微软自己封装了一个数据访问模块, 即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();
//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
浙公网安备 33010602011771号