gpt4 book ai didi

c# - 从阅读器打印出多行

转载 作者:太空宇宙 更新时间:2023-11-03 19:25:35 24 4
gpt4 key购买 nike

下面将从数据库中打印出 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();
}
}
}
}
}

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

最佳答案

这里:

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

此外,由于您是在方法中实例化连接对象,因此您实际上并不需要将它们设为私有(private)字段:

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

关于c# - 从阅读器打印出多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8989023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com