【发布时间】:2018-05-29 23:13:09
【问题描述】:
我想使用SqlDataReader 用我的 SQL Server 数据库中的数据填充用户数组。
这是我目前的代码:
public struct User
{
public int id;
public string log;
public string password;
public User (int id1,string s, s2)
{
id=id1;
log =s;
password=s2;
}
}
User[] al = new User[50];
int i=0;
using (SqlConnection connection = new SqlConnection("string")
{
connection.Open();
SqlCommand command = new SqlCommand("Select [UserName], [Password]. from [TaUser]", connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// populate the al array with the datas from the 3 columns : ID, UserName, Password
}
}
connection.Close();
}
我知道,如果我有一个简单的数组列表,我可以使用 al.Add(""),但是,在涉及结构数组时我会遇到困难。
【问题讨论】:
-
用
.Add将其保存到List<User>,然后调用.ToArray()从列表中获取数组 -
您的结构没有与您的查询相同的字段。例如,结构中没有
UserName字段;相反,它有一个名为log的神秘字段。这是故意的吗?此外,您的查询返回两列,但User的构造函数需要 3 个参数。这是怎么回事? -
@JohnWu imo 在不同的域中拥有不同的属性名称并不罕见
-
我建议您使用只读属性使其不可变,因为可变结构会给您带来很多麻烦。更好的是把它变成一个类,因为它首先作为一个结构没有意义。
-
@dan 很好,如果它们不同,但 OP 需要指定映射,尤其是当属性多于列时。
标签: c# arrays sql-server datareader