数据读取器---获取数据的信息
实例:使用数据读取器获取结果集的信息
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace ResultSetInfo { class Program { static void Main(string[] args) { string connString = @"Data Source=SNH;Initial Catalog=Northwind;Integrated Security=True"; string sql = @"select contactname,contacttitle from customers where contactname like 'M%'"; SqlConnection conn = new SqlConnection(connString); try { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader rdr = cmd.ExecuteReader(); //get column names Console.WriteLine("Column Name:\t{0} {1}", rdr.GetName(0).PadRight(25), rdr.GetName(1)); //get column data types Console.WriteLine("Data Type:\t{0} {1}", rdr.GetDataTypeName(0).PadRight(25), rdr.GetDataTypeName(1)); Console.WriteLine(); while (rdr.Read()) { //get column values for all rows Console.WriteLine("\t\t{0} {1}", rdr.GetString(0).ToString().PadRight(25), rdr.GetString(1)); } //get number of columns Console.WriteLine(); Console.WriteLine("Number of columns in a row: {0}", rdr.FieldCount); // get info about each column Console.WriteLine("'{0} is as index {1} " + "and its type is: {2}", rdr.GetName(0), rdr.GetOrdinal("contactname"), rdr.GetFieldType(0)); Console.WriteLine("'{0}' is at index {1} " + "and its type is: {2}", rdr.GetName(1), rdr.GetOrdinal("contacttitle"), rdr.GetFieldType(1)); rdr.Close(); } catch (SqlException e) { Console.WriteLine("Error: " + e.ToString()); } finally { conn.Close(); } Console.ReadKey(); } } }
示例说明:
GetName方法根据列的索引获取列的名称。rdr.GetName(1)
GetDataTypeName方法返回数据库中的一列的数据类型。rdr.GetDataTypeName(0)
FieldCount属性包含结果集中的列数。在不知道列的名称或其他属性的情况下遍历列时,十分有用。