在ASP.NET中串連SQL Server的簡單方法
來源:互聯網
上載者:User
首先匯入名字空間: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>