SqlDataReader用于高效读取只进只读数据流,使用步骤包括建立连接、执行命令、读取数据和释放资源。需保持连接打开直至读取完成,通过Read()方法逐行读取,用列名或索引获取值,并推荐用using语句确保资源释放。

在C#中,SqlDataReader 用于从数据库高效地读取只进、只读的数据流。它适用于需要快速访问大量数据的场景,比如逐行读取查询结果。
使用 SqlDataReader 的典型流程包括:建立连接、执行命令、读取数据、关闭资源。注意必须保持连接打开直到读取完成。
以下是一个使用 SqlDataReader 读取用户表数据的示例:
using System;
using System.Data;
using Microsoft.Data.SqlClient; // .NET 6+ 使用 Microsoft.Data.SqlClient
class Program
{
static void Main()
{
string connectionString = "Server=localhost;Database=TestDB;User Id=sa;Password=your_password;";
string query = "SELECT Id, Name, Email FROM Users";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32("Id");
string name = reader["Name"].ToString();
string email = reader["Email"] as string;
Console.WriteLine($"ID: {id}, Name: {name}, Email: {email}");
}
reader.Close(); // 关闭读取器
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
} // 连接自动关闭
}
}使用 SqlDataReader 时应注意以下几点以避免常见问题:
基本上就这些。SqlDataReader 轻量高效,适合读取大量数据的场景,但需注意及时释放资源。
以上就是C#中如何使用SqlDataReader读取数据?示例代码是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号