添加相关的命名空间:
using System.Data;
使用Data Access Application Block进行数据的读取和操作,一般分为三步:
1.创建Database对象
2.提供命令参数,如果需要的话
3.执行命令
相关代码表示如下:(非常简单,大家可访照)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using System.Data.SqlClient;
using System.Data.Common;
public partial class testEntLib : System.Web.UI.Page
{
// 创建Database对象
Database db = DatabaseFactory.CreateDatabase();
protected void Page_Load(object sender, EventArgs e)
{
// 使用SQL语句创建DbCommand对象
string sqlCommand = "Select CustomerID, Name, Address, City, Country, PostalCode " +
"From Customers";
DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
//直接获取ds
//DataSet ds = db.ExecuteDataSet(dbCommand);
//根据条件执行存储过程返回ds
DataSet ds = GetProductsInCategory(2);
this.GridView1.DataSource = ds.Tables[0];
this.GridView1.DataBind();
}
//执行存储过程并传递参数,返回DataSet
public DataSet GetProductsInCategory(int Category)
{
string procCommand = "GetProductsByCategory";
DbCommand dbCommand = db.GetStoredProcCommand(procCommand);
// Retrieve products from the specified category.
db.AddInParameter(dbCommand, "CategoryID", DbType.Int32, Category);
// DataSet that will hold the returned results
DataSet productsDataSet = null;
productsDataSet = db.ExecuteDataSet(dbCommand);
// Note: connection was closed by ExecuteDataSet method call
return productsDataSet;
}
/*存储过程进各种参数的处理
Database类提供了如下的方法,用于参数的处理:
AddParameter. 传递参数给存储过程
AddInParameter. 传递输入参数给存储过程
AddOutParameter. 传递输出参数给存储过程
GetParameterValue. 得到指定参数的值
SetParameterValue. 设定参数值
使用示例如下:
Database db = DatabaseFactory.CreateDatabase();
string sqlCommand = "GetProductDetails";
DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand);
db.AddInParameter(dbCommand, "ProductID", DbType.Int32, 5);
db.AddOutParameter(dbCommand, "ProductName", DbType.String, 50);
db.AddOutParameter(dbCommand, "UnitPrice", DbType.Currency, 8);
Database db = DatabaseFactory.CreateDatabase();
DbCommand insertCommand = db.GetStoredProcCommand("AddProduct");
db.AddInParameter(insertCommand, "ProductName", DbType.String, "ProductName", DataRowVersion.Current);
db.AddInParameter(insertCommand, "CategoryID", DbType.Int32, "CategoryID", DataRowVersion.Current);
db.AddInParameter(insertCommand, "UnitPrice", DbType.Currency, "UnitPrice", DataRowVersion.Current);*/
}