SQL Server:返回表中的所有行并读取其值 [英] SQL Server: return all rows in table and read their values

查看:201
本文介绍了SQL Server:返回表中的所有行并读取其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张6列5行的表格.我想选择所有行并使用 SqlDataReader (ASP.NET C#)读取它们.我目前可以使用 dataReader ["columnName"].ToString()访问单个列,并将其存储在字符串变量中.

I have a table with 6 columns and 5 rows. I want to select all rows and read through them using the SqlDataReader (ASP.NET C#). I currently can access single columns using dataReader["columnName"].ToString() and store that in a string variable.

我想逐行阅读各列.

感谢您的帮助.

推荐答案

如果要将行和列存储到某种类型的集合中,可以尝试使用列表和字典",它可以让您添加尽可能多的行.您需要.

If you want to store the rows and columns into a collection of some sort, you can try using a List and Dictionary which will let you add as many rows as you need.

     List<Dictionary<string, string>> rows = new List<Dictionary<string, string>>();
     Dictionary<string, string> column; 
     string sqlQuery = "SELECT USER_ID, FIRSTNAME, LASTNAME FROM USERS";

    SqlCommand command = new SqlCommand(sqlQuery, myConnection);

    try
    {
        myConnection.Open();

        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {    //Every new row will create a new dictionary that holds the columns
             column = new Dictionary<string, string>(); 

             column["USER_ID"] = reader["USER_ID"].ToString();
             column["FIRSTNAME"] = reader["FIRSTNAME"].ToString();
             column["LASTNAME"] = reader["LASTNAME"].ToString();

             rows.Add(column); //Place the dictionary into the list
        }
        reader.Close();
    }
    catch (Exception ex)
    { 
         //If an exception occurs, write it to the console
         Console.WriteLine(ex.ToString());
    }
    finally
    {
        myConnection.Close();
    }

    //Once you've read the rows into the collection you can loop through to                     
    //display the results

    foreach(Dictionary<string, string> column in rows)
    {
        Console.Write(column["USER_ID"]) + " ";
        Console.Write(column["FIRSTNAME"] + " ";
        Console.Write(column["LASTNAME"] + " ";
        Console.WriteLine();
    }

这篇关于SQL Server:返回表中的所有行并读取其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆