.net中简单连接数据库

第一次面试时,技术部的让我对sql数据库中某个表进行分页显示,用程序写,当时怎么也没想起来,今天特意写出来!

代码如下(分页控件下次补充):

1、   Web.config中

<connectionStrings>

        <add name="MyCon" connectionString="Data Source=10.10.100.101;DataBase=OA_murp_DB;uid=sa;pwd=sasa" providerName="System.Data.SqlClient"/>

</connectionStrings>

2、   A.aspx中

<asp:Repeater ID="rt_table" runat="server">

        <HeaderTemplate>

            <table width="800px">

            <thead>

            <tr>

            <td style="width:10%">用户ID</td>

            <td style="width:20%">用户名</td>

            <td style="width:40%">真实姓名</td>

            <td style="width:30%">用户密码</td>

            </tr>

            </thead>

           

        </HeaderTemplate>

        <ItemTemplate>

            <tr>

            <td style="width:10%"><asp:Label ID="lb_userId"runat="server"Text='<%#Eval("u_id") %>'/></td>

            <td style="width:20%"><asp:Label ID="lb_username"runat="server"Text='<%#Eval("u_username") %>'/></td>

            <td style="width:40%"><asp:Label ID="lb_threname"runat="server"Text='<%#Eval("Username") %>'/></td>

            <td style="width:30%"><asp:Label ID="lb_pwd" runat="server"Text='<%#Eval("u_password") %>'/></td>

            </tr>

        </ItemTemplate>

        <FooterTemplate>

        </table>

        </FooterTemplate></asp:Repeater>

3、    A.aspx.cs中     

/// <summary>

    /// 根据Sql语句返回DataTable

    /// </summary>

    /// <paramname="sqlstr"></param>

    /// <returns></returns>

    privateDataTable GetData(stringsqlstr)

    {

        stringcoonStr = ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString;

        SqlConnectionsqlconn = new SqlConnection(coonStr);

 

        SqlCommandsqlcomd = new SqlCommand();

        sqlcomd.Connection =sqlconn;

        sqlcomd.CommandText =sqlstr;

 

        DataTableresultDt = new DataTable();

        SqlDataAdaptersda = new SqlDataAdapter(sqlcomd);

        sda.Fill(resultDt);

        returnresultDt;

}

protected void Page_Load(object sender, EventArgse)

    {

        if(!IsPostBack)

        {

            stringstr = "select top(10) * from users";

            this.rt_table.DataSource=GetData(str);

            rt_table.DataBind();

        }

 

    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章