从阅读器打印出许多行

时间:2012-01-24 15:02:34

标签: c# .net-3.5 asp.net-3.5

以下将从数据库中打印出1行

public partial class Default : System.Web.UI.Page
{
    SqlConnection connection;
    SqlCommand command;
    SqlDataReader reader;

    protected void Page_Load(object sender, EventArgs e)
    {
        using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"]))
        {
            using (command = new SqlCommand("select col1, col2 from table1 where id = @id", connection))
            {
                command.Parameters.Add("@id", SqlDbType.Int, 3).Value = 1;
                connection.Open();

                using (reader = command.ExecuteReader())
                {
                    reader.Read();
                    Div1.InnerHtml = reader["col1"].ToString();
                }
            }
        }
    }
}

这里需要做什么才能打印出所有返回的行?

2 个答案:

答案 0 :(得分:4)

下面:

using (reader = command.ExecuteReader())
{
    var sb = new StringBuilder();
    while (reader.Read())
    {
        sb.Append(reader["col1"].ToString());
    }
    Div1.InnerHtml = sb.ToString();
}

此外,由于您要在方法中实例化连接对象,因此您不需要将它们设置为私有字段:

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (var connection = new SqlConnection(ConfigurationManager.AppSettings["connString"]))
        using (var command = new SqlCommand("select col1, col2 from table1 where id = @id", connection))
        {
            command.Parameters.Add("@id", SqlDbType.Int, 3).Value = 1;
            connection.Open();

            using (var reader = command.ExecuteReader())
            {
                var sb = new StringBuilder();
                while (reader.Read())
                {
                    sb.Append(reader.GetString(reader.GetOrdinal("col1")));
                }
                Div1.InnerHtml = sb.ToString();
            }
        }
    }
}

答案 1 :(得分:2)

将Read调用置于while循环中:

using (var reader = command.ExecuteReader())
{
   var builder = new StringBuilder();
   while (reader.Read()) 
   {
     builder.Append(reader["col1"].ToString());
   }
   Div1.InnerHtml = builder.ToString();
}

顺便说一句,您似乎有一个页面隐藏文件,其主要关注点应该是访问数据库的页面。您可能希望在设计类时考虑SOLID原则。在这种情况下,违反了单一责任原则。遵循这些原则有助于可维护性,代码重用并使重构变得更加容易。