protected void Button1_Click(object sender, EventArgs e)
{
List<Person> list = new List<Person>();
using (SqlConnection conn = new SqlConnection(connectStr))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read()) --在读之前判断是否还有数据
{
list.Add(new Person() { Id = int.Parse(reader["Id"].ToString()), Name = reader["Name"].ToString(), age = int.Parse(reader["age"].ToString()) });
}
}
}
}
测试类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;namespace DataReader
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int age { get; set; }
public string sex { get; set; }
}
}