当我们连接到数据库,进行了想要的查询以后,就可以在网页上显示它们。使用DataReader是一个比较节省服务器资源的选择。DataReader提供了一种只读的、只向前的数据访问方法,因此在访问比较复杂的数据,或者只是想显示某些数据时,DataReader再适合不过了。
DataReader是一个抽象类,因此不能直接实例化,要通过Command对象的ExecuteReader方法来建立。
下面是个例子:
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection Conn = new SqlConnection("server=.;database=northwind;uid=sa;pwd=chengbo;");
SqlCommand Comm = new SqlCommand("SELECT EmployeeID, LastName, BirthDate FROM Employees", Conn );
try
{
Conn.Open();
SqlDataReader reader = Comm.ExecuteReader();
while(reader.Read())
{
//此处使用序数索引器
Response.Write("<P>" + reader[0] + " " + reader[1] + " " + reader[2] + "</P>");
}
reader.Close();
}
catch(SqlException ex)
{
Response.Write(ex.Message);
}
finally
{
Conn.Close();
}
}
代码中有灰色背景的地方使用的是序数索引器,还可以使用列名索引器:
Response.Write("<P>" + reader["EmployeeID"] + " " + reader["LastName"] + " " + reader["BirthDate"] + "</P>");
此外,还可以使用类型访问方法:
Response.Write("<P>" + reader.GetSqlInt32(0).ToString() + " " + reader.GetSqlString(1).ToString() + " " + reader.GetSqlDateTime(2).ToString() + "</P>");
三种方法最终的结果都一样,但是哪种方法性能更好,速度更快呢?
答案是
类型访问 > 序数索引器 > 列名索引器
序数索引是通过列的序数来访问列值的,这种方法不必从行中查找列,而是直接跳到指定的列中进行访问,因而比较省资源,速度较快。
列名索引是通过列的名称来访问列值的,这种方法虽然速度一般,但是它使得代码更易读,因而更易维护,降低了成本。
类型访问和序数索引比较相像,它也包含序数,但它同时指定了数据类型,减少了额外的工作,因而使速度更快,类型更安全。
这里要提到的是,由于我们使用的是MSDE(SQL Server 2000),而.Net Framework提供了专门为SQL Server 7.0及以上版本设计的优化类型方法,所以我们使用了GetSqlInt32、GetSqlString、GetSqlDateTime等优化方法,更为通用的是GetInt32、GetString、GetDateTime等。
GetSqlInt32、GetSqlString、GetSqlDateTime等方法返回的是SqlTypes对象,比如,GetSqlInt32方法返回的是System.Data.SqlTypes.SqlInt32类型而不是System.Int32对象,后者才是GetInt32方法返回的对象,所以我们在每个方法后再调用了ToString方法进行转换,这样才能使用"+"连接,然后输出。
下面是System.Data.SqlTypes 命名空间为 SQL Server 内的本机数据类型提供类。这些类提供了一种较之其他数据类型更安全、更快捷的方法。在可能丢失精度的情况下,在此命名空间中使用这些类有助于防止产生类型转换错误。由于其他数据类型在幕后与 SqlTypes 进行相互转换,所以在此命名空间内显式创建和使用对象将会使代码更快。
下表将 System.Data.SqlTypes 命名空间的成员映射到 Microsoft SQL Server 数据类型及 SqlDbType 枚举的成员。
本机 SQL Server | .NET Framework SqlTypes | .NET Framework SqlDbType |
binary | SqlBinary | Binary |
Bigint | SqlInt64 | BigInt |
Char | SqlString | Char |
datetime | SqlDateTime | DateTime |
decimal | SqlDecimal | Decimal |
Float | SqlDouble | Float |
image | SqlBinary | Image |
Int | SqlInt32 | Int |
Money | SqlMoney | Money |
nchar | SqlString | NChar |
Ntext | SqlString | NText |
nvarchar | SqlString | NVarChar |
Numeric | SqlDecimal | Numeric |
Real | SqlSingle | Real |
smalldatetime | SqlDateTime | SmallDateTime |
smallint | SqlInt16 | SmallInt |
smallmoney | SqlMoney | SmallMoney |
sql_variant | Object | Variant |
sysname | SqlString | VarChar |
text | SqlString | Text |
timestamp | SqlBinary | TimeStamp |
tinyint | SqlByte | TinyInt |
varbinary | SqlBinary | VarBinary |
varchar | SqlString | VarChar |
uniqueidentifier | SqlGuid | UniqueId |