Asp.Net查询MSSQL数据库的一个例子
一:使用System.Data.OleDb
<%@page language="c#" debug="true"%>
<%@Import Namespace="System.Data"%>
<%@Import Namespace="System.Data.OleDb"%>
<script language="c#" runat="server">
public void page_load(Object o,EventArgs e)
{
/**定义相关变量*/
String strConn="provider=sqloledb.1;data source=localhost;initial catalog=pubs;user id=sa;password=lzjliu202080";
String strSQL1="SELECT * FROM authors";
String strSQL2="SELECT * FROM jobs";
String strSQL3="SELECT * FROM sales";
/**建立数据库连接*/
OleDbConnection myConn=new OleDbConnection(strConn);
try
{
/**查询数据*/
OleDbDataAdapter myAdapter1=new OleDbDataAdapter(strSQL1,myConn);
OleDbDataAdapter myAdapter2=new OleDbDataAdapter(strSQL2,myConn);
OleDbDataAdapter myAdapter3=new OleDbDataAdapter(strSQL3,myConn);
/**实例化DataSet*/
DataSet myData=new DataSet();
/**将数据资料存入DataSet*/
myAdapter1.Fill(myData,"authors");
myAdapter2.Fill(myData,"jobs");
myAdapter3.Fill(myData,"sales");
/**设置数据来源*/
myGrid1.DataSource=myData.Tables["authors"].DefaultView;
myGrid2.DataSource=myData.Tables["jobs"].DefaultView;
myGrid3.DataSource=myData.Tables["sales"].DefaultView;
/**数据绑定*/
myGrid1.DataBind();
myGrid2.DataBind();
myGrid3.DataBind();
}
catch(Exception ex)
{
Response.Write("应用程序发生意外错误!");
}
finally
{
/**资源释放*/
//myAdapter1.Close();
//myAdapter2.Close();
//myAdapter3.Close();
myConn.Close();
}
}
</script>
<html>
<head>
<title>Asp.Net数据查询</title>
</head>
<body>
<form runat="server">
<asp:DataGrid id="myGrid1" runat="server"
allowPaging="true"
pageSize="5"
pagerStyle-mode="NumericPages"
borderColor="black"
borderWidth="1"
cellPadding="3"
cellSpacing="0"
GridLines="Both"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
AlternatingItemStyle-BackColor="#eeeeee"/>
<asp:DataGrid id="myGrid2" runat="server"
allowPaging="true"
pageSize="5"
pagerStyle-mode="NumericPages"/>
<asp:DataGrid id="myGrid3" runat="server"
allowPaging="true"
pageSize="5"
pagerStyle-mode="NumericPages"/>
</form>
</body>
</html>
二:使用System.Data.SqlClient
<%@page language="c#" debug="true"%>
<%@Import Namespace="System.Data"%>