数据读取器---使用序数索引器
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace OrdinelIndexer { class Program { static void Main(string[] args) { string connString = @"server=.;integrated security =true;database =northwind"; string sql = @"select companyname,contactname from customers where contactname like 'M%'"; SqlConnection conn = new SqlConnection(connString); try { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader rdr = cmd.ExecuteReader(); Console.WriteLine("\t{0} {1}", "Company Name".PadRight(25), "Contact Name".PadRight(20)); Console.WriteLine("\t{0} {1}", "============".PadRight(25), "============".PadRight(20)); while (rdr.Read()) { Console.WriteLine(" {0} | {1}", rdr[0].ToString().PadLeft(25), rdr[1].ToString().PadLeft(20)); } rdr.Close(); } catch (Exception e) { Console.WriteLine("Error Occurred: " + e); } finally { conn.Close(); } Console.ReadKey(); } } }
由于查询选中了两列,返回的数据只包含由这两列构成的行集合,因此只允许访问两个序数索引器,即0和1.
在while循环中读取每行的数据后,使用序数索引器获取两列的值。返回值的类型是对象,因此需要显式地把这个值转换为字符串,以便利用PadLeft方法格式化输出,所有的字符都是右对齐的,左边填充了一些空格以保持固定的总长度.