天天看点

asp.net连接数据库代码解释

根据自己的理解写的, 可能会有错误

以前刚开始学的时候就觉得连个数据库怎么需要这么多东西, 现在解释下希望可以帮到刚开始学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>