c# - 如何在 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' 的所有数据
解决方案
有几个基本缺陷,但听起来您已经成功检索了至少一个记录或列,所以我会将它们视为简单的拼写错误。
考虑到这一点,仍然需要进行四项更改:
- 对集合使用字符串以外的类型,该类型对您需要的每个属性都有一个位置。
- 在 SQL 字符串的 SELECT 子句中要求多于一列
- 将查询结果中的所有属性与集合一起保存
- 将所有字段写入响应
我还将在这里演示一些其他更改,以帮助展示一些更好的实践。
//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>");
}
推荐阅读
- python - 基于数据框列值的底图散点图颜色
- html - Bootstrap 4 搜索导航栏未显示在移动设备上
- r - 将列表存储在R中for循环内的列表中
- python-3.x - 是什么导致python IDE报告“在'function'中找不到引用'['”
- r - 如何在 R 中重新排列 x 轴上的条形
- javascript - Ngstyle 随机选择项目
- android - Android Intent Whatsapp
- python - keras 风格转移示例有一个无法解释的常数
- python - Matplotlib/SNS:绘制直方图,但在 y 轴上有另一个变量的平均值
- reactjs - React,如何使用单独文件中的菜单来调用 api 并将数据返回到主文件的不同部分