且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server:返回表中的所有行并读取其值

更新时间:2023-02-07 09:18:02

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

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();
    }