C# 如何在ASP.NET C中获取DB关系行中的所有值并将它们分配给变量

C# 如何在ASP.NET C中获取DB关系行中的所有值并将它们分配给变量,c#,asp.net,C#,Asp.net,我试图找到一种方法来访问一行中的所有值 下面的代码返回一个单元格。如果我将select id更改为select*,我可以访问该行,但如何将其拆分 string find_user = "select id from users where userName = '" + un + "'"; using (SqlConnection con = new SqlConnection(cs)) { using (SqlCommand cmd = new SqlCommand(find_use

我试图找到一种方法来访问一行中的所有值

下面的代码返回一个单元格。如果我将select id更改为select*,我可以访问该行,但如何将其拆分

string find_user = "select id from users where userName = '" + un + "'";

using (SqlConnection con = new SqlConnection(cs))
{
    using (SqlCommand cmd = new SqlCommand(find_user, con))
    {
        con.Open();
        user_id = cmd.ExecuteScalar().ToString();

        /* use to pass the info to all the pages */
        Session.Add("u_id", user_id);
    }
}

无法使用.ExecuteScalar访问其他列:

执行查询,并返回查询返回的结果集中第一行的第一列。其他列或行将被忽略

虽然这不是我推荐的路线,但您可以通过在数据读取器上使用索引来迭代字段:

SqlDataReader dataReader = cmd.ExecuteReader();
// for the query's result set, this while loop will go through all the records
while (dataReader.Read())
{
    // for the current record, this for loop will go through all the fields
    for (int i = 0; i < dataReader.FieldCount; i++)
    {
        var value = dataReader[i]; // do what you need with the data here
    }
}
更好的方法是在SQL查询中指定字段名,而不是使用SELECT*,然后通过特定字段名从数据读取器获取值,而不依赖于数据库中字段的顺序

此外,您还存在SQL注入漏洞。您应该查看这意味着什么以及如何参数化查询。

为什么不使用SELECT id、secondColumn、thirdColumn等。。。?但首先你需要了解。