使用DataAdapter填充多个表(利用DataRelation)的实例代码
default.aspx
view code
<%@ page language="c#" autoeventwireup="true" codefile="default.aspx.cs" inherits="_default" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:label id="lbtext" runat="server"></asp:label>
</form>
</body>
</html>
default.aspx.cs
using system;
using system.configuration;
using system.data;
using system.linq;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.htmlcontrols;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.xml.linq;
using system.data.sqlclient;
using system.text;
public partial class _default : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
string connectionstring = configurationsettings.appsettings["strcon"];
sqlconnection mycon = new sqlconnection(connectionstring);//创建数据库连接
string sqlcategory = "select id,c_name from photo_category";//查询相册分类表中信息
string sqlphoto = "select categoryid,title from photo";//查询相册表中信息
sqldataadapter da = new sqldataadapter(sqlcategory, mycon);//创建数据适配器
dataset ds = new dataset();//创建数据集
try
{
if (mycon.state.equals(connectionstate.closed))
{ mycon.open(); }//显式地打开数据库连接
da.fill(ds, "photo_category");//填充相册分类表
da.selectcommand.commandtext = sqlphoto;
da.fill(ds, "photo");//填充相册信息表
}
finally
{
mycon.close();//显式地关闭数据库连接
}
//创建datarelation对象,关联表间关系
datarelation relat = new datarelation("photo_category", ds.tables["photo_category"].columns["id"],ds.tables["photo"].columns["categoryid"]);
ds.relations.add(relat);//添加表间关系
stringbuilder builder = new stringbuilder("");
foreach (datarow row in ds.tables["photo_category"].rows)
{
builder.append("<b>");
builder.append(row["c_name"].tostring());
builder.append("</b><ul>");
datarow[] childrows = row.getchildrows(relat);
foreach (datarow childrow in childrows)
{
builder.append("<li>");
builder.append(childrow["title"].tostring());
builder.append("</li>");
}
builder.append("</ul>");
}
lbtext.text += builder.tostring();//将运行结果输出到页面中
}
}
上一篇: Java线程安全中的单例模式