简体   繁体   中英

SQL Server: return all rows in table and read their values

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.

I want to read through the columns row by row.

Thanks for helping.

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

Based on an MSDN example , here's a straightforward implementation:

    private static void ReadGetOrdinal(string connectionString)
    {
        string queryString = "SELECT DISTINCT CustomerID FROM dbo.Orders;";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using(SqlCommand command = new SqlCommand(queryString, connection))
            {
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {

                    // Call GetOrdinal and assign value to variable. 
                    int customerID = reader.GetOrdinal("CustomerID");

                    // Use variable with GetString inside of loop. 
                    while (reader.Read())
                    {
                        Console.WriteLine("CustomerID={0}", reader.GetString(customerID));
                    }
                }
            }
        }
    }

Here you go,

Member Variables:

static SqlConnection moConnection = new SqlConnection("Data Source=XXX;Initial Catalog=XXX;User ID=XXX;Password=XXX");
static SqlCommand moCommand = new SqlCommand();
static SqlDataAdapter moAdapter = new SqlDataAdapter();
static DataSet moDataSet = new DataSet();
static string msQuery;

In class method, you have to write below code:

DataSet loDataSet = new DataSet();
msQuery = "SELECT * FROM [TableName]";
Execommand(msQuery);
moAdapter.Fill(loDataSet);
DataTable loTable = new DataTable();
loTable = loDataSet.Tables[0];
if (loTable != null && loTable.Rows.Count > 0)
{
    foreach (DataRow foRow in loTable.Rows)
    {
       string lsUserID = Convert.ToString(foRow["UserID"]);
    }
}

Thanks for all of you for helping out. I am answering this to reflect my experience. I used GridView which is a standard control of ASP.NET. It really does the job easily and highly customizable.

a sample code has been added below for further illustration of how it works. If anyone requires help when using it, feel free to post here and I will try my best to help

        <asp:GridView ID="GridView1" runat="server" AllowPaging="True"   
        AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CustomerID"   
        DataSourceID="SqlDataSource1">  
        <Columns>  
            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True"   
                SortExpression="CustomerID" />  
            <asp:BoundField DataField="CompanyName" HeaderText="CompanyName"   
                SortExpression="CompanyName" />  
            <asp:BoundField DataField="ContactName" HeaderText="ContactName"   
                SortExpression="ContactName" />  
            <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle"   
                SortExpression="ContactTitle" />  
            <asp:BoundField DataField="Address" HeaderText="Address"   
                SortExpression="Address" />  
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />  
            <asp:BoundField DataField="Region" HeaderText="Region"   
                SortExpression="Region" />  
            <asp:BoundField DataField="PostalCode" HeaderText="PostalCode"   
                SortExpression="PostalCode" />  
            <asp:BoundField DataField="Country" HeaderText="Country"   
                SortExpression="Country" />  
            <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />  
            <asp:BoundField DataField="Fax" HeaderText="Fax" SortExpression="Fax" />  
        </Columns>  
    </asp:GridView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM