特色栏目

ASP源码

PHP源码

.NET源码

JSP源码

游戏频道
专题合集
关闭菜单
首页> ASP教程> 编写数据库操作类,使ASP.NET中的数据库操作变得简单

编写数据库操作类,使ASP.NET中的数据库操作变得简单

时间:2009-06-25 17:41:52 作者:互联网

作者:Willmove
主页:http://www.amuhouse.com
E-mail: wi***[email protected]">wi***[email protected]
声明:系作者原创作品,转载请注明出处。

ASP.NET中一般都是使用SQL Server作为后台数据库。一般的ASP.NET数据库操作示例程序都是使用单独的数据访问,就是说每个页面都写连接到数据库,存取数据,关闭数据库的代码。这种方式带来了一些弊端,一个就是如果你的数据库改变了,你必须一个页面一个页面的去更改数据库连接代码。
第二个弊端就是代码冗余,很多代码都是重复的,不必要的。
因此,我试图通过一种一致的数据库操作类来实现ASP.NET种的数据访问。

我们就拿一般网站上都会有的新闻发布系统来做例子,它需要一个文章数据库,我们把这个数据库命名为 News_Articles。新闻发布系统涉及到 发布新闻,展示文章,管理文章等。

一篇文章一般都会有标题,作者,发表时间,内容,另外我们需要把它们编号。我们把它写成一个类,叫 Article 类,代码如下:

//***icle.cs
using System;

namespace Ne***Articles.Data
{
 ///


 /// Summary description for Article.
 ///

 public class Article
 {
  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
代码如下


 程序代码

//***icleCollection.cs
using System[color=#0000ff];
using Sy***m.Collections;

namespace Ne***Articles.Data
{
 ///


 /// 文章的集合类,继承于 ArrayList
 ///

 public class ArticleCollection : ArrayList
 {
  public ArticleCollection() : base()
  {
  }

  public ArticleCollection(ICollection c) : base(c)
  {
  }
 }
}[/color]


这个类相当于一个ASP.NET中的DataSet(其实两者很不一样),很简单,主要的目的是把将很多篇文章集合,以便在ASP.NET页面中给DataGrid或者DataList作为数据源,以显示文章。

现在我们可以实现对News_Articles数据库的操作了,我说过,这是一个数据库操作类。不妨命名为 ArticleDb。实现如下:

 程序代码

//***icleDb.cs
using System;
using Sy***m.Configuration;
using Sy***m.Data;
using Sy***m.Data.SqlClient;

namespace Ne***Articles.Data
{
 /**////


 /// 数据库操作类,实现文章数据库的读取,插入,更新,删除
 ///

 public class ArticleDb
 {
  private SqlConnection _conn;       //SQL Server 数据库连接
  private string   _articledb = "News_Articles"; //SQL Server 文章数据库表
 
  /**////
  /// 类的初始化,设置数据库连接
  ///

  public ArticleDb()
  {
   _conn = new SqlConnection(Co***gurationSettings.AppSettings["connectionString"]);
  }

  /**////


  /// 打开数据库连接
  ///

  public void Open()
  {
   if(_c***.State == Co***ctionState.Closed)
    _c***.Open();
  }

  /**////


  /// 关闭数据库连接
  ///

  public void Close()
  {
   if(_c***.State == Co***ctionState.Open)
    _c***.Close();
  }

  /**////


  /// 读取数据库中所有的 文章
  ///

  /// ArticleCollection
  public ArticleCollection GetArticles()
  {
   ArticleCollection articles = new ArticleCollection();
   string sql = "Select * FROM " + _articledb;
   SqlCommand cmd = new SqlCommand(sql,_conn);
   SqlDataReader dr = cm***xecuteReader();
   while(dr.Read())
   {
    Article art = PopulateArticle(dr);
    ar***les.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 = cm***xecuteReader();
   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);

   cm***arameters.Add("@articleId",Sq***Type.Int,4).Value  = ar***le.ID;
   cm***arameters.Add("@topic",Sq***Type.NVarChar,100).Value = ar***le.Topic;
   cm***arameters.Add("@author",Sq***Type.NVarChar,100).Value = ar***le.Author;
   cm***arameters.Add("@content",Sq***Type.NText).Value  = ar***le.Content;
   cm***arameters.Add("@postTime",Sq***Type.DateTime).Value = ar***le.PostTime;

   cm***xecuteNonQuery();

  }


  /**////


  /// 取出数据库中特定作者发表的文章
  ///

  ///
  /// 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 = cm***xecuteReader();

   while (dr.Read())
   {
    Article a = PopulateArticle(dr);
    ar***leCollection.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);
   cm***xecuteNonQuery();
  }

 


  /**////


  /// 通过 SqlDataReader 生成文章对象
  ///

  ///
  ///
  private Article PopulateArticle(SqlDataReader dr)
  {
   Article art = new Article();

   ar***D ; = Co***rt.ToInt32(dr["ID"]);
   ar***uthor = Co***rt.ToString(dr["Author"]);
   ar***opic = Co***rt.ToString(dr["Topic"]);

   ar***ontent = Co***rt.ToString(dr["Content"]);
   ar***ostTime= Co***rt.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);
   cm***arameters.Add("@postID",Sq***Type.Int,4);
   cm***arameters["@postID"].Direction = Pa***eterDirection.Output;

   cm***arameters.Add("@author",Sq***Type.NVarChar,100).Value = ar***le.Author;
   cm***arameters.Add("@topic",Sq***Type.NVarChar,400).Value = ar***le.Topic;
   cm***arameters.Add("@content",Sq***Type.Text).Value   = ar***le.Content;
   cm***arameters.Add("@postTime",Sq***Type.DateTime).Value = ar***le.PostTime;
 
   cm***xecuteNonQuery();

   ar***le.ID = (int)cm***arameters["@postID"].Value;
   return ar***le.ID;
  
  }
 }
}

 

基本的框架已经出来了。如果我们要在一个ASP.NET页面中显示文章数据库 News_Artices的数据,那么仅仅需要添加一个 DataGrid 或者 DataList,然后绑定数据源。例如
De***lt.aspx 中添加一个 DataGrid ,命名为 ArticlesDataGrid,在 后台代码 De***lt.aspx.cs 中添加

 程序代码
using Ne***Articles.Data;


并在 Page_Load 中添加如下的代码:


 程序代码
private void Page_Load(object sender, Sy***m.EventArgs e)
{
 // Put user code to initialize the page here
 ArticleDb myArticleDb = new ArticleDb();
 my***icleDb.Open();
 ArticleCollection articles = my***icleDb.GetArticles();
 th***ArticlesDataGrid.DataSource = articles;
 if(!Pa***IsPostBack)
 {
  th***ArticlesDataGrid.DataBind();
 }

 my***icleDb.Close();
}


这样就可以实现读取文章数据库中所有文章。
如果需要删除一篇文章那么添加如下代码:

 程序代码

 //删除编号为 1 的文章
 my***icleDb.DeleteArticle(1);

插入一篇文章,代码如下:


 程序代码
  //插入一篇新的文章,不需要指定文章编号,文章编号插入成功后由SQL Server返回。
 Article newArticle  = new Article();
 ne***ticle.Author ; = "Willmove";
 ne***ticle.Topic ; = "测试插入一篇新的文章";
 ne***ticle.Content ; = "这是我写的文章的内容";
 ne***ticle.PostTime = Da***ime.Now;
 int articleId = my***icleDb.AddPost(newArticle);


更新一篇文章,代码如下:
 

 程序代码
  //更新一篇文章,注意需要指定文章的编号
 Article updateArticle  = new Article();
 up***eArticle.ID = 3; //注意需要指定文章的编号
 up***eArticle.Author ; = "Willmove";
 up***eArticle.Topic ; = "测试更新数据";
 up***eArticle.Content ; = "这是我更新的文章的内容";
 up***eArticle.PostTime = Da***ime.Now;
 my***icleDb.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 项目源代码
说明:打开项目文件 Ne***Articles.csproj 之前需要先设置 虚拟路径 News_Articles,或者在 Ne***Articles.csproj.webinfo 中更改设置。要正常运行还必须安装有SQL Server 并且安装了文章数据库 News_Articles。项目源代码的根目录下有 SQL 文本文件。

相关文章 最新文章

相关应用

热门文章

猜你喜欢

返回顶部