本教程详细介绍了如何使用SqlDataReader在C#中高效地从SQL数据库中读取数据,并提供了具体的代码示例。
使用SqlDataReader读取数据示例:
```csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
string query = SELECT * FROM Employees;
SqlCommand command = new SqlCommand(query, connection);
try
{
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
int employeeId = reader.GetInt32(0); // 获取员工ID
string name = reader.GetString(1); // 获取姓名
Console.WriteLine(Employee ID: {0}, Name: {1}, employeeId, name);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
```
这段代码展示了如何使用SqlDataReader从SQL Server数据库中读取数据。首先,创建一个SqlConnection实例,并提供连接字符串以建立到数据库的连接。然后定义查询语句并执行它,最后通过循环遍历结果集来获取和显示员工信息(例如ID和姓名)。注意需要处理可能发生的异常情况。