在ASP.NET中访问SQL Server
2024-07-10 12:55:55
供稿:网友
在asp.net中访问sql server数据库有两种方法,它们是system.data.oledb和system.data.sqlclient.下面这段程序以system.data.sqlclient为例访问本地数据库服务器.
首先导入名字空间:system.data和system.data.sqlclient.详细代码看源程序.
<%@ import namespace="system.data" %>
<%@ import namespace="system.data.sqlclient" %>
<html>
<script language="c#" runat="server">
protected void page_load(object src, eventargs e )
{
sqlconnection myconn = new sqlconnection("server=localhost;uid=sa;pwd=;database=pubs");
//创建对象sqlconnection
string strsql="select au_id,au_lname,au_fname,phone,address,city,zip from authors";
sqldataadapter mycmd = new sqldataadapter(strsql, myconn);
//创建对象sqldataadapter
dataset ds = new dataset();
//创建对象dataset
mycmd.fill(ds);
//填充数据到dataset
dataview source = new dataview(ds.tables[0]);
mydatagrid.datasource = source ;
mydatagrid.databind();
//将数据绑定到datagrid
}
</script>
<body>
<h3><font face="verdana">simple select to a datagrid control
</font></h3>
<asp:datagrid id="mydatagrid" runat="server"
width="600"
backcolor="#ccccff"
bordercolor="black"
showfooter="false"
cellpadding=3
cellspacing="0"
font-name="verdana"
font-size="8pt"
headerstyle-backcolor="#aaaadd"
maintainstate="false"
/>
</body>
</html>