asp.net串連資料庫代碼解釋

來源:互聯網
上載者:User

根據自己的理解寫的, 可能會有錯誤

以前剛開始學的時候就覺得連個資料庫怎麼需要這麼多東西, 現在解釋下希望可以幫到剛開始學asp.net的朋友


資料擷取階段:

protected SqlConnection conn;//建立資料庫的連線物件
protected SqlDataAdapter da;//建立資料庫的查詢對象
protected DataSet ds;//建立DataSet資料表對象以實現斷開式串連
protected SqlCommand comm;//建立資料庫的操作對象
protected void Page_Load(object sender, EventArgs e)
 {
 conn=new SqlConnection("Data Source=localhost;Initial Catalog=nd_data;User ID=sa;Password=aaaaaa");//取連接字串, 同時建立串連
 da= new SqlDataAdapter();//初始化查詢對象
 da.SelectCommand= new SqlCommand("select name,id from xs Order by id,name DESC", conn);進行一個查詢id和姓名的資料庫操作
 ds= new DataSet();初始化DataSet對象
try
 {
 conn.Open();//開啟串連
 da.Fill(ds,"abs");//擷取資料,同時存放在一個名為"abs"的表中
 conn.Close();//關閉串連
 }
catch (SqlException e1)//錯誤處理
 {
 Response.Write(e1.ToString());
 }

資料顯示階段:

PagedDataSource objPds= new PagedDataSource();//建立一個作用於控制項的資料來源對象
 objPds.DataSource= ds.Tables["abs"].DefaultView;//傳入之前儲存的"abs"表
 DataListname.DataSource= objPds;//資料來源對象傳入DataList控制項
 DataListname.DataBind();//DataList控制項顯示資料資訊


前台資料顯示方法:

<ItemTemplate>//DataList資料控制項範本
<asp:Label ID="lbNwes" runat="server" Text='<%#Eval("id")%>'></asp:Label>//顯示id
<asp:Label ID="lbTime" runat="server" Text='<%#Eval("name")%>'></asp:Label>//顯示name
</ItemTemplate>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.