DataReader的使用方法

  using System.Data.SqlClient;

  using System.Data;

  // 建立连接

  string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword";

  SqlConnection connection = new SqlConnection(connectionString);

  connection.Open();

  // 创建DataReader对象

  string query = "SELECT * FROM myTable";

  SqlCommand command = new SqlCommand(query, connection);

  SqlDataReader reader = command.ExecuteReader();

  // 读取数据

  while (reader.Read())

  {

  string column1 = reader["column1"].ToString();

  int column2 = Convert.ToInt32(reader["column2"]);

  // 处理每一行数据的逻辑

  }

  // 关闭连接

  reader.Close();

  connection.Close();登录后复制