最简单的ASP.NET数据库操作示例源代码

作者:网络 来源:佚名 更新时间:2009-03-10 19:20:20 点击:

using system;
using system.collections;
using system.configuration;
using system.data;
using system.linq;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.htmlcontrols;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.xml.linq;
using system.data.sqlclient;
public partial class _default : system.web.ui.page
{
    protected void page_load(object sender, eventargs e)
    {
      // sqlconnection con = new sqlconnection("server=dbtalbe;uid=sa;pwd=sa;database=addb;");
        //con.open();
        sqlconnection con = new sqlconnection(configurationmanager.appsettings["strconn"]);
        con.open();
        /*写入数据库
        sqlcommand cmd = new sqlcommand("insert into [ad_sort] ([sortname])  values  ('首页广告')",con);
        cmd.executenonquery();
        response.write("写入成功!");
        con.close();
        */
        string strsql = "select * from ad_sort order by id desc";
        //读取数据
        sqldataadapter sda = new sqldataadapter(strsql, con);
        dataset ds = new dataset();
        sda.fill(ds, "ad_sort");
        this.hotcommentlist.datasource = ds;
        this.hotcommentlist.databind();

        //读取单个数据
        sqldataadapter set = new sqldataadapter(strsql, con);
        dataset rs = new dataset();
        set.fill(rs,"ad_sort");
        //datarowview mydrview = rs.tables["ad_sort"].defaultview[0];
        this.sortname.innerhtml = convert.tostring(rs.tables["ad_sort"].defaultview[0].row[1]);
        /*
        sqldataadapter set = new sqldataadapter(strsql,con);
        dataset rs = new dataset();
        set.fill(rs,"ad_sort");
        this.sortname.innerhtml = convert.tostring(rs.tables["ad_sort"].defaultview[0].row[1]);
        this.sortname.innerhtml = convert.tostring(rs.tables["ad_sort"].defaultview[0].row[1]);
        */

        sqlcommand cmd = new sqlcommand(strsql, con);
        sqldatareader res1 = cmd.executereader();
        string listbody="";
        listbody += ("<table border=0 ");
        listbody+=("<tr><td>executereader读取数据</td></tr>");
        listbody += ("<tr><th>编号</th><th>名称</th></tr>");
        while (res1.read())
        {
            listbody += ("<tr>");
            listbody += ("<td align='center'>" + res1["id"].tostring() + "</td>");
            listbody += ("<td align='left'>" + res1["sortname"].tostring() + "</td>");
            listbody += ("</tr>");
        }
        listbody += ("</table>");
        list2.innerhtml = listbody;
        res1.close();

        con.close();
    }
}