以下将只从数据库中打印出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();
}
另外,由于您要在方法内部实例化连接对象,因此实际上不需要将它们设置为私有字段:
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/