作者:Willmove
主頁:http://www.amuhouse.com
E-mail: willmove@gmail.com
ASP.NET中一般都是使用SQL Server作為后臺(tái)數(shù)據(jù)庫。一般的ASP.NET數(shù)據(jù)庫操作示例程序都是使用單獨(dú)的數(shù)據(jù)訪問,就是說每個(gè)頁面都寫連接到數(shù)據(jù)庫,存取數(shù)據(jù),關(guān)閉數(shù)據(jù)庫的代碼。這種方式帶來了一些弊端,一個(gè)就是如果你的數(shù)據(jù)庫改變了,你必須一個(gè)頁面一個(gè)頁面的去更改數(shù)據(jù)庫連接代碼。
第二個(gè)弊端就是代碼冗余,很多代碼都是重復(fù)的,不必要的。
因此,我試圖通過一種一致的數(shù)據(jù)庫操作類來實(shí)現(xiàn)ASP.NET種的數(shù)據(jù)訪問。
我們就拿一般網(wǎng)站上都會(huì)有的新聞發(fā)布系統(tǒng)來做例子,它需要一個(gè)文章數(shù)據(jù)庫,我們把這個(gè)數(shù)據(jù)庫命名為 News_Articles。新聞發(fā)布系統(tǒng)涉及到 發(fā)布新聞,展示文章,管理文章等。
一篇文章一般都會(huì)有標(biāo)題,作者,發(fā)表時(shí)間,內(nèi)容,另外我們需要把它們編號(hào)。我們把它寫成一個(gè)類,叫 Article 類,代碼如下:
//Article.cs
using System;
namespace News_Articles.Data
{
/// <summary>
/// Summary description for Article.
/// </summary>
public class Article
{
private int _id; //文章編號(hào)
private string _author; //文章的作者
private string _topic; //文章的標(biāo)題
private DateTime _postTime; //文章的發(fā)表時(shí)間
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; }
}
}
}
然后我們寫一個(gè)文章集合類 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)
{
}
}
}
這個(gè)類相當(dāng)于一個(gè)ASP.NET中的DataSet(其實(shí)兩者很不一樣),很簡單,主要的目的是把將很多篇文章集合,以便在ASP.NET頁面中給DataGrid或者DataList作為數(shù)據(jù)源,以顯示文章。
現(xiàn)在我們可以實(shí)現(xiàn)對(duì)News_Articles數(shù)據(jù)庫的操作了,我說過,這是一個(gè)數(shù)據(jù)庫操作類。不妨命名為 ArticleDb。實(shí)現(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ù)庫操作類,實(shí)現(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è)置數(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>
/// 關(guān)閉數(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>
/// 給定一個(gè)文章編號(hào), 讀取數(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ù)庫記錄,注意需要設(shè)定文章的編號(hào)
/// </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>
/// 刪除給定編號(hào)的一篇文章
/// </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 生成文章對(duì)象
/// </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ù)庫中,返回文章的編號(hào)
/// </summary>
/// <param name="article"></param>
/// <returns>剛剛插入的文章的編號(hào)</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)出來了。如果我們要在一個(gè)ASP.NET頁面中顯示文章數(shù)據(jù)庫 News_Artices的數(shù)據(jù),那么僅僅需要添加一個(gè) DataGrid 或者 DataList,然后綁定數(shù)據(jù)源。例如
在 Default.aspx 中添加一個(gè) DataGrid ,命名為 ArticlesDataGrid,在 后臺(tái)代碼 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();
}
這樣就可以實(shí)現(xiàn)讀取文章數(shù)據(jù)庫中所有文章。
如果需要?jiǎng)h除一篇文章那么添加如下代碼:
//刪除編號(hào)為 1 的文章
myArticleDb.DeleteArticle(1);
插入一篇文章,代碼如下:
//插入一篇新的文章,不需要指定文章編號(hào),文章編號(hào)插入成功后由SQL Server返回。
Article newArticle = new Article();
newArticle.Author = "Willmove";
newArticle.Topic = "測(cè)試插入一篇新的文章";
newArticle.Content = "這是我寫的文章的內(nèi)容";
newArticle.PostTime = DateTime.Now;
int articleId = myArticleDb.AddPost(newArticle);
更新一篇文章,代碼如下:
//更新一篇文章,注意需要指定文章的編號(hào)
Article updateArticle = new Article();
updateArticle.ID = 3; //注意需要指定文章的編號(hào)
updateArticle.Author = "Willmove";
updateArticle.Topic = "測(cè)試更新數(shù)據(jù)";
updateArticle.Content = "這是我更新的文章的內(nèi)容";
updateArticle.PostTime = DateTime.Now;
myArticleDb.UpdateArticle(updateArticle);
以上只是一個(gè)框架,具體的實(shí)現(xiàn)還有很多細(xì)節(jié)沒有列出來。但是基于上面的框架,你可以比較方便的寫出對(duì)數(shù)據(jù)庫操作的代碼。
附1:News_Articles 數(shù)據(jù)庫的字段
字段名 描述 數(shù)據(jù)類型 長度 是否可為空
ID 文章編號(hào) int 4 否
Topic 文章標(biāo)題 nvarchar 100 否
Author 作者 nvarchar 100 是
Content 文章內(nèi)容 ntext 16 否
PostTime 發(fā)表時(shí)間 datetime 8 否
其中 PostTime 的默認(rèn)值可以設(shè)置為(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 項(xiàng)目源代碼
打開項(xiàng)目文件 News_Articles.csproj 之前需要先設(shè)置 虛擬路徑 News_Articles,或者在 News_Articles.csproj.webinfo 中更改設(shè)置。要正常運(yùn)行還必須安裝有SQL Server 并且安裝了文章數(shù)據(jù)庫 News_Articles。項(xiàng)目源代碼的根目錄下有 SQL 文本文件。