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

时间:2015-03-15 02:39:31

标签: c# sql asp.net sql-server

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

我想逐行阅读这些列。

感谢您的帮助。

4 个答案:

答案 0 :(得分:10)

如果要将行和列存储到某种类型的集合中,可以尝试使用List和Dictionary,这样可以根据需要添加任意数量的行。

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

答案 1 :(得分:2)

基于MSDN example,这是一个简单的实现:

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

答案 2 :(得分:1)

你走了,

会员变量:

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;

在类方法中,您必须编写以下代码:

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"]);
    }
}

答案 3 :(得分:0)

感谢大家帮忙。我正在回答这个以反映我的经历。我使用的是GridView,它是ASP.NET的标准控件。它确实可以轻松实现高度可定制的工作。

下面添加了示例代码,以进一步说明其工作原理。如果有人在使用时需要帮助,请随时在此发布,我会尽力帮助

        <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>