首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用SqlDataReader在结构数组中存储多个值

如何使用SqlDataReader在结构数组中存储多个值
EN

Stack Overflow用户
提问于 2018-05-30 07:13:09
回答 2查看 662关注 0票数 0

我想使用SqlDataReader用我的SQL Server数据库中的数据填充用户数组。

这是我到目前为止的代码:

代码语言:javascript
复制
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(""),然而,当涉及到结构数组时,我很难做到。

EN

回答 2

Stack Overflow用户

发布于 2018-05-30 07:36:56

你的代码中有很多错误。

首先,你的用户构造函数无效,它应该是:

代码语言:javascript
复制
public User(int id1, string s, string s2)

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

第三,使用List而不是array可能更好。

有了所有这些,这应该是可行的

代码语言:javascript
复制
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()
票数 1
EN

Stack Overflow用户

发布于 2018-05-30 07:29:26

我建议这样做:

代码语言:javascript
复制
SqlDataReader dataReader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(dataReader);

然后像这样读出DataTable:

代码语言:javascript
复制
string name = dataTable.Rows[0]["UserName"] as string;

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50594250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档