【问题标题】:How to store multiple values in a struct array using SqlDataReader如何使用 SqlDataReader 在结构数组中存储多个值
【发布时间】: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


【解决方案1】:

您的代码中有很多错误。

首先,你的 User 构造函数无效,应该是:

public User(int id1, string s, string s2)

其次,您的查询不返回用户 ID。

第三,使用 List 而不是数组可能会更好。

所有这些,这应该可以工作

List<User> userList = new List<User>() ;
using (SqlConnection connection = new SqlConnection("string")
{
connection.Open();

SqlCommand command = new SqlCommand("Select [Id], [UserName], [Password]. from [TaUser]", connection);

using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        var id = reader.GetInt32(0);
        var userName = reader.GetString(1);
        var pwd = reader.GetString(2);
        var user = new User(id, userName, pwd);
        userList.Add(user);
    }
}
connection.Close();

// if you really need an array, do it here
var al = userList.ToArray()

【讨论】:

    【解决方案2】:

    我建议这样做:

    SqlDataReader dataReader = cmd.ExecuteReader();
    DataTable dataTable = new DataTable();
    dataTable.Load(dataReader);
    

    然后像这样读出那个DataTable:

    string name = dataTable.Rows[0]["UserName"] as string;
    

    然后用收集到的信息填充你的用户结构。工作完成了吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      相关资源
      最近更新 更多