小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

編寫數(shù)據(jù)庫操作類,使ASP.NET 中的數(shù)據(jù)庫操作變得簡單

 kommy 2007-09-24

編寫數(shù)據(jù)庫操作類,使ASP.NET 中的數(shù)據(jù)庫操作變得簡單

作者:Willmove
主頁:http://www.
E-mail: willmove@gmail.com

ASP.NET中一般都是使用SQL Server作為后臺數(shù)據(jù)庫。一般的ASP.NET數(shù)據(jù)庫操作示例程序都是使用單獨的數(shù)據(jù)訪問,就是說每個頁面都寫連接到數(shù)據(jù)庫,存取數(shù)據(jù),關閉數(shù)據(jù)庫的代碼。這種方式帶來了一些弊端,一個就是如果你的數(shù)據(jù)庫改變了,你必須一個頁面一個頁面的去更改數(shù)據(jù)庫連接代碼。
第二個弊端就是代碼冗余,很多代碼都是重復的,不必要的。
因此,我試圖通過一種一致的數(shù)據(jù)庫操作類來實現(xiàn)ASP.NET種的數(shù)據(jù)訪問。

我們就拿一般網(wǎng)站上都會有的新聞發(fā)布系統(tǒng)來做例子,它需要一個文章數(shù)據(jù)庫,我們把這個數(shù)據(jù)庫命名為 News_Articles。新聞發(fā)布系統(tǒng)涉及到 發(fā)布新聞,展示文章,管理文章等。

一篇文章一般都會有標題,作者,發(fā)表時間,內(nèi)容,另外我們需要把它們編號。我們把它寫成一個類,叫 Article 類,代碼如下:

//Article.cs
using System;

namespace News_Articles.Data
{
 /// <summary>
 /// Summary description for Article.
 /// </summary>
 public class Article
 {
  private int _id;   //文章編號
  private string _author;   //文章的作者
  private string _topic;   //文章的標題
  private DateTime _postTime;  //文章的發(fā)表時間
  private string _content;  //文章內(nèi)容

  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
{
 /// <summary>
 /// 文章的集合類,繼承于 ArrayList
 /// </summary>
 public class ArticleCollection : ArrayList
 {
  public ArticleCollection() : base()
  {
  }

  public ArticleCollection(ICollection c) : base(c)
  {
  }
 }
}


這個類相當于一個ASP.NET中的DataSet(其實兩者很不一樣),很簡單,主要的目的是把將很多篇文章集合,以便在ASP.NET頁面中給DataGrid或者DataList作為數(shù)據(jù)源,以顯示文章。

現(xiàn)在我們可以實現(xiàn)對News_Articles數(shù)據(jù)庫的操作了,我說過,這是一個數(shù)據(jù)庫操作類。不妨命名為 ArticleDb。實現(xiàn)如下:

//ArticleDb.cs
using System;
using System.Configuration;  //配置文件
using System.Data;
using System.Data.SqlClient;  //System.Data.SqlClient 命名空間是 SQL Server 的 .NET Framework 數(shù)據(jù)提供程序。

namespace News_Articles.Data
{
 /// <summary>
 /// 數(shù)據(jù)庫操作類,實現(xiàn)文章數(shù)據(jù)庫的讀取,插入,更新,刪除
 /// </summary>
 public class ArticleDb
         //定義類別為ArticleDb
 {
  private SqlConnection _conn; //SQL Server 數(shù)據(jù)庫連接
  private string   _articledb = "News_Articles"; //SQL Server 文章數(shù)據(jù)庫表
  
  /// <summary>
  /// 類的初始化,設置數(shù)據(jù)庫連接
  /// </summary>
  public ArticleDb()
  {
   _conn = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
  }

  /// <summary>
  /// 打開數(shù)據(jù)庫連接
  /// </summary>
  public void Open()
  {
   if(_conn.State == ConnectionState.Closed)
    _conn.Open();
  }

  /// <summary>
  /// 關閉數(shù)據(jù)庫連接
  /// </summary>
  public void Close()
  {
   if(_conn.State == ConnectionState.Open)
    _conn.Close();
  }

  /// <summary>
  /// 讀取數(shù)據(jù)庫中所有的 文章
  /// </summary>
  /// <returns>ArticleCollection</returns>
  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;
  }

  
  /// <summary>
  /// 給定一個文章編號, 讀取數(shù)據(jù)庫中的一篇文章
  /// </summary>
  /// <returns>Article</returns>
  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;
  }

  /// <summary>
  /// 更新數(shù)據(jù)庫記錄,注意需要設定文章的編號
  /// </summary>
  /// <param name="article"></param>
  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();

  }


  /// <summary>
  /// 取出數(shù)據(jù)庫中特定作者發(fā)表的文章
  /// </summary>
  /// <param name="author"></param>
  /// <returns>ArticleCollection</returns>
  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;
   
  }


  /// <summary>
  /// 刪除給定編號的一篇文章
  /// </summary>
  /// <param name="articleID"></param>
  public void DeleteArticle(int articleID)
  {
   string sql = "DELETE FROM " + _articledb + " WHERE ID='" + articleID + "'";
   SqlCommand cmd = new SqlCommand(sql, _conn);
   cmd.ExecuteNonQuery();
  }

 


  /// <summary>
  /// 通過 SqlDataReader 生成文章對象
  /// </summary>
  /// <param name="dr"></param>
  /// <returns></returns>
  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;
  }

 

  /// <summary>
  /// 增加一篇文章到數(shù)據(jù)庫中,返回文章的編號
  /// </summary>
  /// <param name="article"></param>
  /// <returns>剛剛插入的文章的編號</returns>
  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;
   
  }
 }
}

 

基本的框架已經(jīng)出來了。如果我們要在一個ASP.NET頁面中顯示文章數(shù)據(jù)庫 News_Artices的數(shù)據(jù),那么僅僅需要添加一個 DataGrid 或者 DataList,然后綁定數(shù)據(jù)源。例如
在 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();
}

這樣就可以實現(xiàn)讀取文章數(shù)據(jù)庫中所有文章。
如果需要刪除一篇文章那么添加如下代碼:

 //刪除編號為 1 的文章
 myArticleDb.DeleteArticle(1);

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

 //插入一篇新的文章,不需要指定文章編號,文章編號插入成功后由SQL Server返回。
 Article newArticle  = new Article();
 newArticle.Author  = "Willmove";
 newArticle.Topic   = "測試插入一篇新的文章";
 newArticle.Content  = "這是我寫的文章的內(nèi)容";
 newArticle.PostTime = DateTime.Now;
 int articleId = myArticleDb.AddPost(newArticle);

更新一篇文章,代碼如下:
 
 //更新一篇文章,注意需要指定文章的編號
 Article updateArticle  = new Article();
 updateArticle.ID = 3; //注意需要指定文章的編號
 updateArticle.Author  = "Willmove";
 updateArticle.Topic   = "測試更新數(shù)據(jù)";
 updateArticle.Content  = "這是我更新的文章的內(nèi)容";
 updateArticle.PostTime = DateTime.Now;
 myArticleDb.UpdateArticle(updateArticle);

以上只是一個框架,具體的實現(xiàn)還有很多細節(jié)沒有列出來。但是基于上面的框架,你可以比較方便的寫出對數(shù)據(jù)庫操作的代碼。


附1:News_Articles 數(shù)據(jù)庫的字段
字段名  描述  數(shù)據(jù)類型  長度  是否可為空
ID  文章編號   int    4     否
Topic  文章標題 nvarchar  100     否
Author  作者  nvarchar  100     是
Content  文章內(nèi)容   ntext    16     否
PostTime 發(fā)表時間 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 并且安裝了文章數(shù)據(jù)庫 News_Articles。項目源代碼的根目錄下有 SQL 文本文件。

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多