ASP.NET入门数据篇

 更新时间:2006年07月14日 00:00:00   作者:  

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

数据库连接篇

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

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

数据列表显示篇,如图:

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('您真的要删除这条记录吗?')){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='" + ProductId + "'";
        SqlCommand cmd_Exeits = new SqlCommand(sql_Exeits, myconn);
        myconn.Open();
        SqlDataReader rdr = cmd_Exeits.ExecuteReader();
        while (rdr.Read())
        {
            Response.Write("<script language='JavaScript'>");
            Response.Write("alert('对不起,该产品编号已经存在!')");
            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('" + ProductId + "','" + CategoryId + "','" + Name + "','" + Description + "','" + Price + "')";
        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='" + CategoryId + "',Name='" + Name + "',Description='" + Description + "',Price='" + Price + "' 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('保存成功!')</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");
        }
    }

 

例子下载

相关文章

  • .NET提取 Thread 中返回值详情

    .NET提取 Thread 中返回值详情

    这篇文章主要介绍了.NET提取 Thread 中返回值详情,关于如何获取 Thread 中的返回值,不同的版本有不同的解决方案。需要的朋友可以参考一下
    2022-01-01
  • DataGridView控件详细介绍

    DataGridView控件详细介绍

    DataGridView是用于Windows Froms 2.0的新网格控件。它可以取代先前版本中DataGrid控件,它易于使用并高度可定制,支持很多我们的用户需要的特性
    2012-11-11
  • 详解如何使用Net将HTML简历导出为PDF格式

    详解如何使用Net将HTML简历导出为PDF格式

    这篇文章主要为大家介绍了详解如何使用Net将HTML简历导出为PDF格式详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • ASP.NET webUploader上传大视频文件相关web.config配置

    ASP.NET webUploader上传大视频文件相关web.config配置

    本文主要介绍了webUploader上传大视频文件相关web.config的配置。具有一定的参考价值,下面跟着小编一起来看下吧
    2017-01-01
  • .Net Core HttpClient处理响应压缩详细

    .Net Core HttpClient处理响应压缩详细

    .Net Core作为后起之秀直接将HttpClient扶正,并且在此基础上改良了HttpClientFactory,接下来我们就来探究一下在.Net Core中使用HttpClient处理响应压缩的机制。,需要的朋友可以参考下面文章的具体内容
    2021-09-09
  • upload上传单张图片

    upload上传单张图片

    这篇文章主要介绍了upload上传单张图片的代码,需要的朋友可以参考下。
    2015-07-07
  • .NET 6新特性试用Timer类之PeriodicTimer 

    .NET 6新特性试用Timer类之PeriodicTimer 

    这篇文章主要介绍了.NET 6新特性试用Timer类之PeriodicTimer,PeriodicTimer与其他Timer需要创建事件回调不同,下,下面文章详细介绍PeriodicTimer的使用方式,需要的朋友可以参考一下
    2022-02-02
  • ASP.NET Core 中间件的使用之全局异常处理机制

    ASP.NET Core 中间件的使用之全局异常处理机制

    我们今天这篇文章就来说说代码异常问题怎么快速定位,减少不必要的时间浪费。异常是一种运行时错误,当异常没有得到适当的处理,很可能会导致你的程序意外终止。下面雄安边将详细介绍,需要的朋友可以参考下
    2021-09-09
  • 深入分析XmlSerializer对象的Xml序列化与反序列化的示例详解

    深入分析XmlSerializer对象的Xml序列化与反序列化的示例详解

    本篇文章是对XmlSerializer 对象的Xml序列化与反序列化的应用进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • ASP.NET Core MVC 依赖注入View与Controller

    ASP.NET Core MVC 依赖注入View与Controller

    本文重点给大家介绍的是ASP.NET Core MVC 之依赖注入 View 和ASP.NET Core MVC 之依赖注入 Controller的相关资料,需要的小伙伴可以参考下面文章具体内容
    2021-09-09

最新评论