多个活动的结果集(MARS)
多个活动结果集 (MARS) 是用于 SQL Server 2005 的一项新功能,允许在单个连接上执行多个批处理。要在以前版本的 SQL Server 上使用 SqlDataReader 对象访问多个结果集,必须对每个 SqlCommand 对象使用独立的 SqlConnection 对象。但是,如果对 SQL Server 2005 启用了 MARS,使用的每个命令对象将向该连接添加一个会话。
小例:(sql语句 自己构建)
在连接字符串中启用和禁用 MARS,启用:MultipleActiveResultSets=True,
不然会报错:已有打开的与此命令相关联的 DataReader,必须首先将它关闭。
---------------MARS.aspx.cs---------------------------------------------
public partial class MARS : System.Web.UI.Page
{
SqlConnection DBCon;
protected void Page_Load(object sender, EventArgs e)
{
//在连接字符串中启用和禁用 MARS,启用:MultipleActiveResultSets=True,不然会报错
using (DBCon = new SqlConnection("uid=sa;password=123456;database=study;server=.;MultipleActiveResultSets=True"))
{
SqlCommand command = new SqlCommand("select book_Id,book_Author from book", DBCon);
DBCon.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
gvOrders.DataSource = reader;
gvOrders.DataBind();
}
}
}
protected void gvOrders_RowDataBound(object sender, GridViewRowEventArgs e)
{
IDataRecord record = e.Row.DataItem as IDataRecord;
Label lblOrderDetail = e.Row.FindControl("lblOrderDetail") as Label;
if ((record == null) || (lblOrderDetail == null))
return;
SqlCommand command = new SqlCommand("select book_Name from book where book_Id=" + Convert.ToInt32(record["book_Id"]), DBCon);
using (SqlDataReader readerDetail = command.ExecuteReader())
{
while (readerDetail.Read())
{
lblOrderDetail.Text += readerDetail[0].ToString() + "<br/>";
}
}
}
}
-----------------------MARS.aspx---------------------------------------------
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvOrders_RowDataBound">
<Columns>
<asp:BoundField HeaderText="编号" DataField="book_Id" />
<asp:BoundField HeaderText="作者" DataField="book_Author" />
<asp:TemplateField>
<HeaderTemplate>
order Detail(名字)
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblOrderDetail" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
----------------------------------------------------------------
线程安全性:MARS 操作不是线程安全的。
更过信息 请参考MSDN