如何在C#中将数据库查询结果存储到ArrayList或List中
在C#中将数据库数据存入List/ArrayList的实现方案
嘿,我来帮你搞定这个需求!先梳理下你现有代码的小问题,再给你更规范、健壮的实现方式,同时覆盖List和ArrayList两种场景。
先修正你现有代码的问题
你的思路是对的,但有几处细节需要调整:
- 代码里写了
dr1.GetValue(0),但实际定义的DataReader是dr,这里会直接报错 - 数据库连接、SqlCommand、SqlDataReader都是非托管资源,必须确保及时释放,用
using语句是最稳妥的方式,能自动帮你处理资源回收 - 连接字符串建议放在配置文件里,别硬编码在代码里,后续维护更方便
修正后的基础List实现
// 推荐把连接字符串放在App.config/Web.config中,这里示例直接写 string connectionString = "<CONNECTION STRING>"; List<string> employeeCodes = new List<string>(); // using语句会自动释放资源,不用手动Close/Dispose using (SqlConnection cn = new SqlConnection(connectionString)) using (SqlCommand cmd = new SqlCommand("Select code from employee where Left='Y'", cn)) { cn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { // 增加空值判断,避免转换失败 string code = dr.IsDBNull(0) ? string.Empty : dr.GetString(0); employeeCodes.Add(code); } } } // 遍历示例 foreach (string code in employeeCodes) { Console.WriteLine($"员工编号:{code}"); }
如果要使用ArrayList(仅作兼容参考,不推荐)
ArrayList是.NET早期的非泛型集合,现在更建议用泛型List
string connectionString = "<CONNECTION STRING>"; ArrayList employeeCodes = new ArrayList(); using (SqlConnection cn = new SqlConnection(connectionString)) using (SqlCommand cmd = new SqlCommand("Select code from employee where Left='Y'", cn)) { cn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { string code = dr.IsDBNull(0) ? string.Empty : dr.GetString(0); employeeCodes.Add(code); } } } // 遍历ArrayList需要强制转换类型 foreach (string code in employeeCodes) { Console.WriteLine($"员工编号:{code}"); }
进阶:存储完整员工对象(更符合面向对象思想)
如果需要获取员工的多个字段(比如姓名、离职状态),建议先定义一个Employee类,再用List<Employee>存储,这样代码可读性和扩展性更强:
定义Employee实体类
public class Employee { public string Code { get; set; } public string Name { get; set; } public string LeftStatus { get; set; } // 避开SQL关键字"Left"作为属性名 }
读取数据到List
string connectionString = "<CONNECTION STRING>"; List<Employee> employees = new List<Employee>(); using (SqlConnection cn = new SqlConnection(connectionString)) using (SqlCommand cmd = new SqlCommand("Select code, Name, Left from employee where Left='Y'", cn)) { cn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { Employee emp = new Employee { Code = dr.IsDBNull(0) ? string.Empty : dr.GetString(0), Name = dr.IsDBNull(1) ? string.Empty : dr.GetString(1), LeftStatus = dr.IsDBNull(2) ? string.Empty : dr.GetString(2) }; employees.Add(emp); } } } // 遍历输出完整员工信息 foreach (Employee emp in employees) { Console.WriteLine($"编号:{emp.Code},姓名:{emp.Name},是否离职:{emp.LeftStatus}"); }
几个最佳实践提醒
- 永远用
using管理数据库相关资源,避免连接泄漏 - 连接字符串存配置文件,方便后续修改
- 如果查询有动态条件,一定要用参数化查询,防止SQL注入
- 优先选择泛型List
而非ArrayList,获得类型安全和更好的性能
内容的提问来源于stack exchange,提问作者Gulshan Sonwar
相关产品推荐
相关产品推荐

