人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

July 26, 2006

正确使用DataSet和DataReader

Filed under: SQL&DB Accessing

By Riven Huang 2006.07.26
参照
Why I Don’t Use DataSets in My ASP.NET Applications(by Scott Michell)
http://aspnet.4guysfromrolla.com/articles/050405-1.aspx

Performance Comparison: Data Access Techniques
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/bdadotnetarch031.asp

首先需要理解DataSet 和 DataReader的设计目标:
DataSet可以理解成一个小型的,存在于内存中的数据库,包含多个data table,table之间
可存在约束关系.
DataSet和数据库无关,由DataAdapter来负责对数据库的处理,一旦数据填充结束,就和数据库
断开连接.
DataSet对XML的支持比较好.

DataReader可以理解成程序和数据库之间的桥梁.只能顺序的,从数据库中读取记录.
DataReader是和数据库相关的,所以存在sql, ole等多个版本的DataReader.

从使用上来看,

使用DataReader需要以下步骤:
// 1. 建立连接
SqlConnection myConnection = new SqlConnection(conn);

// 2. 执行查询
SqlCommand myCommand = new SqlCommand(myConnection, sqlText);

SqlReader myReader = myCommand.ExecuteReader();

// 3. Read
while(myReader.Read())
{

}

// 4. Close connection
myConnection.Close();

使用DataSet需要以下步骤:
// 1. 建立连接
SqlConnection myConnection = new SqlConnection(conn);

// 2. 生成command 和 adapter
SqlCommand myCommand = new SqlCommand(myConnection, sqlText);
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);

// 3. 生成dataset并填充
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);

// 4. Close connection
myConnection.Close();

如果使用UIControlo显示数据,对于dataset和datareader的操作是相同的:
把dataset或datareader赋给control的DataSource属性,
再调用control的DataBind()方法.

比较:
DataSet的性能比DataReader差很对,同时占用大量的内存.

何时使用DataSet:
1.数据传输.
2.桌面应用.

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2006/07/26/p130/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham