asp.net中读取数据库的两种方式

      编程开发 2006-11-9 18:17

在asp.net中,读取数据库中的数据可以使用DataReader和DataSet 两种方式,两者的差异如下:


使用Dataset对象读取数据大致需要以下5个步骤:

(1)建立数据库链接,可以选用SQLConnection或者OleDbConnection。

(2)将查询保存在SQLDataAdapter或者oledbDataAdapter对象中。

(3)使用DataAdapter对象的Fill方法将数据填充到DataSet中的DataTable中。

(4)为DataTable对象建立DataView对象以显示数据,这一步可以省略。

(5)将DataView或者DataSet绑定到Server Control上。


使用DataReader读取数据大致需要以下6个步骤:

(1)建立数据库链接,可以选SQLConnection或者OLeDbConnection。

(2)使用Connection对象的open方法打开数据库链接。

(3)将查询保存在SQLCommand或者OleDbCommand对象中。

(4)调用Command对象的ExecuteReader方法,将数据读入DataReader对象中。

(5)调用DataReader的Read或者Get方法读取—笔数据,以便显示。

(6)调用Connection对象的Close方法,关闭数据序链接。

例子:

string strDSN = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("data.mdb");
string strSQL = "SELECT * FROM Project where id=" + Convert.ToInt32(Request.QueryString["Project_ID"]) ;
 
// create Objects of ADOConnection and ADOCommand
OleDbConnection myConn = new OleDbConnection(strDSN);
OleDbCommand myCmd = new OleDbCommand( strSQL, myConn );
OleDbDataReader datareader = null;
try
{
 myConn.Open();
 datareader = myCmd.ExecuteReader();
 while (datareader.Read() )
 {
 ProjectName.Text=datareader["Project_Name"].ToString();
 ProjectManager.Text=datareader["Project_Manager"].ToString(); 
 }
}
catch (Exception e)
{
 string Messate = e.Message;
}
finally
{
 myConn.Close();
}
标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commenttime}{commentauthor}

{CommentUrl}
{commentcontent}