首页 > 解决方案 > 如何在 C# 中将数据列表从数据库存储到 ArrayList 或 List

问题描述

表:员工

code|Name|Left
----+----+----
1   | A  | Y
2   | B  | N
3   | C  | N
4   | D  | Y
5   | E  | N
6   | F  | Y

现在我在做

        SqlConnection cn=new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        cn.ConnectionString="<CONNECTION STRING>"
        List<string> str = new List<string>();
        cmd.Connection=cn;
        cmd.Connection.Open();
        cmd.CommandText="Select code from employee where Left='Y'";
        SqlDataReader dr=cmd.executeReader();
        while(dr.Read())
        {
                       str.Add(dr1.GetValue(0).ToString());

        }

        foreach (string p in str)
        {
                 Response.Write(p);
        }

此代码仅获取 1 个数据,我如何获取 Left='Y' 的所有数据

标签: c#asp.netsql-server

解决方案


有几个基本缺陷,但听起来您已经成功检索了至少一个记录或列,所以我会将它们视为简单的拼写错误。

考虑到这一点,仍然需要进行四项更改:

  1. 对集合使用字符串以外的类型,该类型对您需要的每个属性都有一个位置。
  2. 在 SQL 字符串的 SELECT 子句中要求多于一列
  3. 将查询结果中的所有属性与集合一起保存
  4. 将所有字段写入响应

我还将在这里演示一些其他更改,以帮助展示一些更好的实践。

//Change #1 -- new type with space for each attribute
public class Employee
{
    public string Name {get;set;}
    public string code {get;set;}
    public bool Left {get;set;}
}

// ...

public IEnumerable<Employee> GetEmployees(bool Left)
{
    //Change #2 -- ask for other fields in the SQL select clause
    string sql = "SELECT code, Name, Left FROM employee WHERE Left= @Left";

    using (var cn = new SqlConnection("<CONNECTION STRING>"))
    using (var cmd = new SqlCommand(sql, cn))
    {
        cmd.Parameters.Add("@Left", SqlDbType.Char, 1).Value = Left?"Y":"N";
        cn.Open();

        using (var rdr = cmd.ExecuteReader())
        {
            while(rdr.Read())
            {
                //Change #3 -- use all fields from the query results 
                yield return new Employee() {
                    Name = rdr["Name"], 
                    code = rdr["code"], 
                    Left = (rdr["Left"] == "Y")?true:false
                };
            }
            rdr.Close();
        }
    }
}

// ...

var employees = GetEmployees(true);
foreach (var e in employees)
{ 
    //Change #4 -- Write all fields to the response.
    Response.Write($"<span>{e.Name}</span><span>{e.code}</span><span>{e.Left}</span>");
}

推荐阅读