在ASP.NET中訪問SQL Server
發(fā)表時(shí)間:2024-05-23 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]在ASP.NET中訪問SQL Server數(shù)據(jù)庫有兩種方法,它們是System.Data.OleDb和System.Data.SqlClient.下面這段程序以System.Data.SqlClient為例訪問本地?cái)?shù)據(jù)庫服務(wù)器.首先導(dǎo)入名字空間:System.Data和System.Data.Sq...
在ASP.NET中訪問SQL Server數(shù)據(jù)庫有兩種方法,它們是System.Data.OleDb和System.Data.SqlClient.下面這段程序以System.Data.SqlClient為例訪問本地?cái)?shù)據(jù)庫服務(wù)器.
首先導(dǎo)入名字空間:System.Data和System.Data.SqlClient.詳細(xì)代碼看源程序.
<%@ 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");
//創(chuàng)建對(duì)象SqlConnection
string strSQL="SELECT au_id,au_lname,au_fname,phone,address,city,zip FROM authors";
SqlDataAdapter myCmd = new SqlDataAdapter(strSQL, myConn);
//創(chuàng)建對(duì)象SqlDataAdapter
DataSet ds = new DataSet();
//創(chuàng)建對(duì)象DataSet
myCmd.Fill(ds);
//填充數(shù)據(jù)到Dataset
DataView source = new DataView(ds.Tables[0]);
MyDataGrid.DataSource = source ;
MyDataGrid.DataBind();
//將數(shù)據(jù)綁定到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>