c# - 从 SqlDataReader 填充通用列表

sqlserver

1个回答

写回答

Young阳仔

2025-06-30 11:05

+ 关注

服务器
服务器

使用C#编程语言时,我们经常需要从数据库中获取数据并填充到通用列表中。为了实现这一目标,我们可以使用SqlDataReader类来检索数据库查询的结果,并将其转换为我们所需的通用列表。

在开始之前,我们需要先建立与数据库的连接,并执行一个查询语句。下面是一个简单的示例代码,演示了如何连接到数据库并执行一个查询:

csharp

string connectionString = "Data Source=服务器地址;Initial Catalog=数据库名;User ID=用户名;Password=密码;";

string query = "SELECT * FROM 表名";

using (SqlConnection connection = new SqlConnection(connectionString))

{

SqlCommand command = new SqlCommand(query, connection);

connection.Open();

using (SqlDataReader reader = command.ExecuteReader())

{

while (reader.Read())

{

// 在这里处理每一行的数据

}

}

}

在上面的代码中,我们首先定义了数据库的连接字符串和查询语句。然后,我们创建了一个SqlConnection对象,并将连接字符串传递给它。接下来,我们创建了一个SqlCommand对象,并将查询语句和SqlConnection对象传递给它。然后,我们打开了数据库连接,并使用ExecuteReader方法执行查询,并将结果存储在一个SqlDataReader对象中。

现在,我们已经获得了查询结果的SqlDataReader对象,接下来的步骤就是将这些结果填充到通用列表中。我们可以通过在while循环中读取每一行的数据,并将其转换为我们所需的类型来实现这一目标。

假设我们有一个名为Person的类,它有两个属性:Id和Name。我们可以使用下面的代码将查询结果填充到一个List列表中:

csharp

List<Person> personList = new List<Person>();

while (reader.Read())

{

int id = (int)reader["Id"];

string name = (string)reader["Name"];

Person person = new Person();

person.Id = id;

person.Name = name;

personList.Add(person);

}

在上面的代码中,我们首先从SqlDataReader对象中读取Id和Name属性的值,并将它们转换为适当的类型。然后,我们创建一个Person对象,并将这些值分配给它的属性。最后,我们将Person对象添加到personList列表中。

通过这种方式,我们可以逐行读取查询结果,并将其转换为我们所需的类型,并将其填充到通用列表中。这样,我们就可以在代码中方便地使用这些数据了。

案例代码实现:从数据库查询结果填充通用列表

下面是一个完整的例子,演示了如何从数据库查询结果中填充一个通用列表:

csharp

using System;

using System.Collections.Generic;

using System.Data.SqlClient;

namespace SqlDataReaderExample

{

class Person

{

public int Id { get; set; }

public string Name { get; set; }

}

class Program

{

static void MAIn(string[] args)

{

string connectionString = "Data Source=服务器地址;Initial Catalog=数据库名;User ID=用户名;Password=密码;";

string query = "SELECT * FROM 表名";

List<Person> personList = new List<Person>();

using (SqlConnection connection = new SqlConnection(connectionString))

{

SqlCommand command = new SqlCommand(query, connection);

connection.Open();

using (SqlDataReader reader = command.ExecuteReader())

{

while (reader.Read())

{

int id = (int)reader["Id"];

string name = (string)reader["Name"];

Person person = new Person();

person.Id = id;

person.Name = name;

personList.Add(person);

}

}

}

foreach (Person person in personList)

{

Console.WriteLine("Id: " + person.Id + ", Name: " + person.Name);

}

}

}

}

在上面的代码中,我们首先定义了一个Person类,它具有Id和Name属性。然后,在MAIn方法中,我们创建了一个空的personList列表。接下来,我们通过与数据库建立连接和执行查询的代码来填充这个列表。最后,我们使用foreach循环遍历personList列表,并将每个Person对象的属性值打印到控制台上。

通过这个例子,我们可以看到如何使用SqlDataReader类从数据库查询结果中填充通用列表。这种方法可以帮助我们轻松地处理数据库中的数据,并在C#程序中使用它们。无论我们需要从数据库中检索多少行数据,使用这种方法都是非常高效和可靠的。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号