zoukankan      html  css  js  c++  java
  • 编写数据库操作类,使ASP.NET中的数据库操作变得简单

    转载Willmove的文章
    
    ASP.NET中一般都是使用SQL Server作为后台数据库。一般的ASP.NET数据库操作示例程序都是使用单独的数据访问,就是说每个页面都写连接到数据库,存取数据,关闭数据库的代码。这种方式带来了一些弊端,一个就是如果你的数据库改变了,你必须一个页面一个页面的去更改数据库连接代码。
    第二个弊端就是代码冗余,很多代码都是重复的,不必要的。
    因此,我试图通过一种一致的数据库操作类来实现ASP.NET种的数据访问。
    
    我们就拿一般网站上都会有的新闻发布系统来做例子,它需要一个文章数据库,我们把这个数据库命名为 News_Articles。新闻发布系统涉及到 发布新闻,展示文章,管理文章等。
    
    一篇文章一般都会有标题,作者,发表时间,内容,另外我们需要把它们编号。我们把它写成一个类,叫 Article 类,代码如下:
    
    //Article.cs
    using System;
    
    namespace News_Articles.Data
    {
     ///
     /// Summary description for Article.
     ///
     public > {
     private int _id; //文章编号
     private string _author; //文章的作者
     private string _topic; //文章的标题
     private DateTime _postTime; //文章的发表时间
     private string _content; //文章内容
    
     public int ID
     {
     get { return _id;}
     set { _id = value;}
     }
     public string Author
     {
     get { return _author; }
     set { _author = value; }
     }
     public string Topic
     {
     get { return _topic; }
     set { _topic = value; }
     }
     public string Content
     {
     get { return _content; }
     set { _content = value; }
     }
     public DateTime PostTime
     {
     get { return _postTime; }
     set { _postTime = value; }
     }
     }
    }
    
    
    然后我们写一个文章集合类 ArticleCollection
    代码如下
    
    
     程序代码
    
    //ArticleCollection.cs
    using System;
    using System.Collections;
    
    namespace News_Articles.Data
    {
     ///
     /// 文章的集合类,继承于 ArrayList
     ///
     public > {
     public ArticleCollection() : base()
     {
     }
    
     public ArticleCollection(ICollection c) : base(c)
     {
     }
     }
    }

    
    
    这个类相当于一个ASP.NET中的DataSet(其实两者很不一样),很简单,主要的目的是把将很多篇文章集合,以便在ASP.NET页面中给DataGrid或者DataList作为数据源,以显示文章。
    
    现在我们可以实现对News_Articles数据库的操作了,我说过,这是一个数据库操作类。不妨命名为 ArticleDb。实现如下:
    
     程序代码
    
    //ArticleDb.cs
    using System;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace News_Articles.Data
    {
     /**////
     /// 数据库操作类,实现文章数据库的读取,插入,更新,删除
     ///
     public > {
     private SqlConnection _conn; //SQL Server 数据库连接
     private string _articledb = "News_Articles"; //SQL Server 文章数据库表
    
     /**////
     /// 类的初始化,设置数据库连接
     ///
     public ArticleDb()
     {
     _conn = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
     }
    
     /**////
     /// 打开数据库连接
     ///
     public void Open()
     {
     if(_conn.State == ConnectionState.Closed)
     _conn.Open();
     }
    
     /**////
     /// 关闭数据库连接
     ///
     public void Close()
     {
     if(_conn.State == ConnectionState.Open)
     _conn.Close();
     }
    
     /**////
     /// 读取数据库中所有的 文章
     ///
     /// ArticleCollection
     public ArticleCollection GetArticles()
     {
     ArticleCollection articles = new ArticleCollection();
     string sql = "Select * FROM " + _articledb;
     SqlCommand cmd = new SqlCommand(sql,_conn);
     SqlDataReader dr = cmd.ExecuteReader();
     while(dr.Read())
     {
     Article art = PopulateArticle(dr);
     articles.Add(art);
     }
     dr.Close();
     return articles;
     }
    
    
     /**////
     /// 给定一个文章编号, 读取数据库中的一篇文章
     ///
     /// Article
     public Article GetArticle(int articleId)
     {
     string sql = "Select * FROM " + _articledb + "Where ID='" + articleId + "'";
     SqlCommand cmd = new SqlCommand(sql,_conn);
     SqlDataReader dr = cmd.ExecuteReader();
     Article article = PopulateArticle(dr);
     dr.Close();
     return article;
     }
    
     /**////
     /// 更新数据库记录,注意需要设定文章的编号
     ///
     /// public void UpdateArticle(Article article)
     {
     string sql = "Update " + _articledb +" SET Topic=@topic,Author=@author,Content=@content,PostTime=@postTime"
     + " Where ID = @articleId";
     SqlCommand cmd = new SqlCommand(sql,_conn);
    
     cmd.Parameters.Add("@articleId",SqlDbType.Int,4).Value = article.ID;
     cmd.Parameters.Add("@topic",SqlDbType.NVarChar,100).Value = article.Topic;
     cmd.Parameters.Add("@author",SqlDbType.NVarChar,100).Value = article.Author;
     cmd.Parameters.Add("@content",SqlDbType.NText).Value = article.Content;
     cmd.Parameters.Add("@postTime",SqlDbType.DateTime).Value = article.PostTime;
    
     cmd.ExecuteNonQuery();
    
     }
    
    
     /**////
     /// 取出数据库中特定作者发表的文章
     ///
     /// /// ArticleCollection
     public ArticleCollection GetArticlesByAuthor(string author)
     {
     string sql = "Select * FROM " + _articledb +" Where Author='" + author + "'";
     SqlCommand cmd = new SqlCommand(sql, _conn);
    
     ArticleCollection articleCollection = new ArticleCollection();
    
     SqlDataReader dr = cmd.ExecuteReader();
    
     while (dr.Read())
     {
     Article a = PopulateArticle(dr);
     articleCollection.Add(a);
     }
     dr.Close();
     return articleCollection;
    
     }
    
    
     /**////
     /// 删除给定编号的一篇文章
     ///
     /// public void DeleteArticle(int articleID)
     {
     string sql = "Delete FROM " + _articledb + " Where ID='" + articleID + "'";
     SqlCommand cmd = new SqlCommand(sql, _conn);
     cmd.ExecuteNonQuery();
     }
    
    
    
    
     /**////
     /// 通过 SqlDataReader 生成文章对象
     ///
     /// ///
     private Article PopulateArticle(SqlDataReader dr)
     {
     Article art = new Article();
    
     art.ID = Convert.ToInt32(dr["ID"]);
     art.Author = Convert.ToString(dr["Author"]);
     art.Topic = Convert.ToString(dr["Topic"]);
    
     art.Content = Convert.ToString(dr["Content"]);
     art.PostTime= Convert.ToDateTime(dr["PostTime"]);
    
     return art;
     }
    
    
    
     /**////
     /// 增加一篇文章到数据库中,返回文章的编号
     ///
     /// /// 刚刚插入的文章的编号
     public int AddPost(Article article)
     {
     string sql = "Insert INTO " + _articledb +"(Author,Topic,Content,PostTime)"+
     "VALUES(@author, @topic, @content, @postTime) "+
     "Select @postID = @@IDENTITY";
     SqlCommand cmd = new SqlCommand(sql,_conn);
     cmd.Parameters.Add("@postID",SqlDbType.Int,4);
     cmd.Parameters["@postID"].Direction = ParameterDirection.Output;
    
     cmd.Parameters.Add("@author",SqlDbType.NVarChar,100).Value = article.Author;
     cmd.Parameters.Add("@topic",SqlDbType.NVarChar,400).Value = article.Topic;
     cmd.Parameters.Add("@content",SqlDbType.Text).Value = article.Content;
     cmd.Parameters.Add("@postTime",SqlDbType.DateTime).Value = article.PostTime;
    
     cmd.ExecuteNonQuery();
    
     article.ID = (int)cmd.Parameters["@postID"].Value;
     return article.ID;
    
     }
     }
    }
    
    
    
    基本的框架已经出来了。如果我们要在一个ASP.NET页面中显示文章数据库 News_Artices的数据,那么仅仅需要添加一个 DataGrid 或者 DataList,然后绑定数据源。例如
    在 Default.aspx 中添加一个 DataGrid ,命名为 ArticlesDataGrid,在 后台代码 Default.aspx.cs 中添加
    
     程序代码
    using News_Articles.Data;
    
    
    并在 Page_Load 中添加如下的代码:
    
    
     程序代码
    private void Page_Load(object sender, System.EventArgs e)
    {
     // Put user code to initialize the page here
     ArticleDb myArticleDb = new ArticleDb();
     myArticleDb.Open();
     ArticleCollection articles = myArticleDb.GetArticles();
     this.ArticlesDataGrid.DataSource = articles;
     if(!Page.IsPostBack)
     {
     this.ArticlesDataGrid.DataBind();
     }
    
     myArticleDb.Close();
    }
    
    
    这样就可以实现读取文章数据库中所有文章。
    如果需要删除一篇文章那么添加如下代码:
    
     程序代码
    
     //删除编号为 1 的文章
     myArticleDb.DeleteArticle(1);
    
    插入一篇文章,代码如下:
    
    
     程序代码
     //插入一篇新的文章,不需要指定文章编号,文章编号插入成功后由SQL Server返回。
     Article newArticle = new Article();
     newArticle.Author = "Willmove";
     newArticle.Topic = "测试插入一篇新的文章";
     newArticle.Content = "这是我写的文章的内容";
     newArticle.PostTime = DateTime.Now;
     int articleId = myArticleDb.AddPost(newArticle);
    
    
    更新一篇文章,代码如下:
    
    
     程序代码
     //更新一篇文章,注意需要指定文章的编号
     Article updateArticle = new Article();
     updateArticle.ID = 3; //注意需要指定文章的编号
     updateArticle.Author = "Willmove";
     updateArticle.Topic = "测试更新数据";
     updateArticle.Content = "这是我更新的文章的内容";
     updateArticle.PostTime = DateTime.Now;
     myArticleDb.UpdateArticle(updateArticle);
    
    
    以上只是一个框架,具体的实现还有很多细节没有列出来。但是基于上面的框架,你可以比较方便的写出对数据库操作的代码。另外一个建议就是把上面的数据库访问的 SQL 语句写成数据库存储过程,比如 添加一篇文章:
    
     程序代码
    Create PROCEDURE AddPost
    (
     @ID int OUTPUT,
     @Author nvarchar(100),
     @Topic nvarchar(100),
     @Content ntext,
     @PostTime datetime
    )
    AS
    Insert INTO News_Articles(Author, Topic, Content, PostTime) VALUES (@Author, @Topic, @Content, @PostTime);
     Select @ID = @@IDENTITY
    GO
    
    
    附1:News_Articles 数据库的字段
    
    
     程序代码
    
    字段名 描述 数据类型 长度 是否可为空
    ID 文章编号 int 4 否
    Topic 文章标题 nvarchar 100 否
    Author 作者 nvarchar 100 是
    Content 文章内容 ntext 16 否
    PostTime 发表时间 datetime 8 否
    
    其中 PostTime 的默认值可以设置为(getutcdate())
    
    SQL 语句是
    
     Create TABLE [News_Articles] (
     [ID] [int] IDENTITY (1, 1) NOT NULL ,
     [Topic] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL ,
     [Author] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
     [Content] [ntext] COLLATE Chinese_PRC_CI_AS NOT NULL ,
     [PostTime] [datetime] NOT NULL CONSTRAINT [DF_News_Articles_PostTime] DEFAULT (getutcdate())
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    GO
    
    附2:News_Articles 项目源代码
    说明:打开项目文件 News_Articles.csproj 之前需要先设置 虚拟路径 News_Articles,或者在 News_Articles.csproj.webinfo 中更改设置。要正常运行还必须安装有SQL Server 并且安装了文章数据库 News_Articles。项目源代码的根目录下有 SQL 文本文件。

  • 相关阅读:
    QT中的qmake详解
    Qt setStyleSheet 添加背景色/背景图片(取消背景色,读取本地文件作为背景色)
    目标HttpController在ASP.NET Web API中是如何被激活的:目标HttpController的选择
    分页写法小结
    SharePoint 2013 搜索高级配置(Search Scope)
    Scut游戏服务器免费开源框架-3
    物理数据模型(PDM)->概念数据模型 (CDM)->面向对象模型 (OOM):适用于已经设计好数据库表结构了。
    一种不错的扩展方式
    ORM框架
    代码最简化
  • 原文地址:https://www.cnblogs.com/sontin/p/1929825.html
Copyright © 2011-2022 走看看