在ASP.NET中訪問SQL Server

來源:互聯網
上載者:User
asp.net|server|訪問 在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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.