登录  /  注册

ASP.NET数据入门

巴扎黑
发布: 2017-05-22 23:03:29
原创
1222人浏览过

对于网站编程的初学者来说,总是会上网找些源码来看,但久而久之还是停留在改代码的阶段,并不明白怎样去写一个完整的网站程序.有见如此我就开始写这样的文章(c#版),不足之处请批评指正.

数据库连接篇

在WEB项目里看到Web.config配置文件,在configuration这行加入下面代码用于和SQL服务器进行连接

<appSettings>
<!-- 数据库连接字符串 -->
<add key="ConnStr" value="Data Source=localhost;database=company;UID=sa;Password=;Persist Security Info=True;" />
</appSettings>
登录后复制

数据列表显示篇,如图:

ASP.NET数据入门

using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//引用命名空间:SQL托管,配置文件
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page 
{
    protected SqlConnection myconn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
    //读取web.config配置文件中的数据库连接字符串,并连接到指定的数据库
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)//判断页面是否第一次运行
     {
          string strsql="select * from Product";//定义一个数据库的查询字符串
                DataSet ds = new DataSet();
                myconn.Open();//打开数据库连接
                SqlDataAdapter command = new SqlDataAdapter(strsql,myconn);//表示用于填充DataSet 和更新SQL Server 数据库的一组数据命令和一个数据库连接 
                command.Fill(ds, "Product");
                productList.DataSource = ds.Tables[0].DefaultView;
                productList.DataBind();
                ds.Clear();
          myconn.Close();//关闭数据库连接
            }
 }
    protected void grid_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        foreach (System.Web.UI.WebControls.HyperLink link in e.Item.Cells[7].Controls)
        {
            link.Attributes.Add("onClick", "if (!window.confirm(&#39;您真的要删除这条记录吗?&#39;)){return false;}");
        }
    }
}
登录后复制

数据添加篇

protected void btnAdd_Click(object sender, EventArgs e)
    {
        string ProductId = this.txtProductId.Text;
        string CategoryId = this.txtCategoryId.Text;
        string Name = this.txtName.Text;
        string Description = this.txtDescription.Text;
        string Price =this.txtPrice.Text;
        string sql_Exeits = "select * from Product where ProductId=&#39;" + ProductId + "&#39;";
        SqlCommand cmd_Exeits = new SqlCommand(sql_Exeits, myconn);
        myconn.Open();
        SqlDataReader rdr = cmd_Exeits.ExecuteReader();
        while (rdr.Read())
        {
            Response.Write("<script language=&#39;JavaScript&#39;>");
            Response.Write("alert(&#39;对不起,该产品编号已经存在!&#39;)");
            Response.Write("</script>");
            this.txtCategoryId.Text = "";
            this.txtDescription.Text = "";
            this.txtName.Text = "";
            this.txtPrice.Text = "";
            this.txtProductId.Text = "";
            return;
        }
        rdr.Close();

        string sql_add = "insert into Product(ProductId,CategoryId,Name,Description,Price)values(&#39;" + ProductId + "&#39;,&#39;" + CategoryId + "&#39;,&#39;" + Name + "&#39;,&#39;" + Description + "&#39;,&#39;" + Price + "&#39;)";
        SqlCommand cmd_add = new SqlCommand(sql_add, myconn);//SqlCommand:表示要对SQL Server数据库执行的一个Transact-SQL语句或存储过程
        cmd_add.ExecuteNonQuery();//对连接执行Transact-SQL语句并返回受影响的行数。对于 UPDATE、INSERT 和 DELETE 语句,返回值为该命令所影响的行数。对于所有其他类型的语句,返回值为 -1。如果发生回滚,返回值也为 -1。
        myconn.Dispose();
        myconn.Close();
    }
[/CODE

[COLOR=Red]数据显示篇[/COLOR]
[CODE]
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string id = Request.Params["id"];
            if (id == null || id.Trim() == "")
            {
                Response.Redirect("default.aspx");
                Response.End();
            }
            else
            {
                string sql_show = "select * from Product Where ProductId=" + id;
                SqlCommand cmd_show = new SqlCommand(sql_show, conn);
                conn.Open();
                SqlDataReader rd_show = cmd_show.ExecuteReader();//使用SqlDataReader对象读取并返回一个记录集
                shows.DataSource = rd_show;//指向数据源
                shows.DataBind();//绑定数据
                rd_show.Close();//关闭SqlDataReader
             }
         }
    }
登录后复制

数据修改篇

  protected void btnAdd_Click(object sender, EventArgs e)
    {
        string ProductId = this.lblProductId.Text;
        string CategoryId = this.txtCategoryId.Text;
        string Name = this.txtName.Text;
        string Description = this.txtDescription.Text;
        decimal Price = decimal.Parse(this.txtPrice.Text);
        string sql_edit = "update Product set CategoryId=&#39;" + CategoryId + "&#39;,Name=&#39;" + Name + "&#39;,Description=&#39;" + Description + "&#39;,Price=&#39;" + Price + "&#39; where ProductId =" + ProductId;
        SqlCommand cmd_edit = new SqlCommand(sql_edit, conn);
        conn.Open();
        cmd_edit.ExecuteNonQuery();
        conn.Close();
        Response.Write("<script language=javascript>window.alert(&#39;保存成功!&#39;)</script>");
        Response.Redirect("show.aspx?id=" + ProductId);
    }
登录后复制

数据删除篇

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string ProductId = Request.Params["id"];
            string sql_del = "delete from Product where ProductId=" + ProductId;
            SqlCommand cmd_del = new SqlCommand(sql_del, conn);
            conn.Open();
            cmd_del.ExecuteNonQuery();
            conn.Close();
            Response.Redirect("default.aspx");
        }
    }
登录后复制

以上就是ASP.NET数据入门的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号