c#读取SqlDataReader中的数据
时间: 2024-11-09 09:27:22 浏览: 58
在C#中,你可以使用ADO.NET库中的`SqlDataReader`类来从SQL查询结果集中读取数据。以下是一个基本步骤:
1. **连接到数据库**:
首先,你需要创建一个`SqlConnection`对象并打开连接到数据库。
```csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
}
```
2. **执行SQL查询**:
使用`SqlCommand`执行SQL命令,并将查询结果设置为`SqlDataReader`。
```csharp
using (SqlCommand command = new SqlCommand(query, connection))
{
SqlDataReader reader = command.ExecuteReader();
}
```
3. **遍历数据**:
使用`reader.Read()`方法逐行读取数据,直到所有记录都被处理完毕。每一行的数据可以分别通过列名获取。
```csharp
while (reader.Read())
{
string column1Value = reader.GetString("Column1");
int column2Value = reader.GetInt32("Column2");
// ... 读取其他列的值
}
```
4. **关闭资源**:
完成操作后,记得关闭`SqlDataReader`和`SqlConnection`。
```csharp
reader.Close(); // 关闭SqlDataReader
connection.Close(); // 关闭SqlConnection
```
阅读全文
相关推荐


















