现在的位置: 首页 > 综合 > 正文

C# 使用数据读取器

2013年10月12日 ⁄ 综合 ⁄ 共 2227字 ⁄ 字号 评论关闭

很久以前就借了一本《Beginning C# Databases From Novice to Professional》,最近闲来无事终于可以拜读一下。读来发现自己之前的数据库操作是何等的粗鄙。今天 抽时间记录下一些关于数据读取器有关的内容。

在本书后面的数据集时提及“如果只想读取数据和显示数据,则只需使用数据读取器”,“如果需要处理数据,然后更新数据库,就需要使用数据集”

下面给出一个实例

using System;

using System.Data;

using System.Data.SqlClient;

namespace DataReader
{
    class Program
    {
        static void Main(string[] args)
        {
             string connString = @"Data Source=localhost;Initial Catalog=mydatabase; Integrated Security=SSPI";
            string sql = @"select * from mytable";
            SqlConnection conn = new SqlConnection(connString);
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);

                //SqlDataReader类是抽象类,不能显示实例化。必须执行SqlCommand的ExecuteReader方法获得SqlDataReader实例
                SqlDataReader reader = cmd.ExecuteReader(); 

               //Read方法如果存在下一行就返回true,并向前移动游标;如果没有下一行,该方法就返回false
                while (reader.Read())
                {
                    Console.WriteLine("databack with {0} columes", reader[0]);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error occurred:" + e);
            }
            finally
            {
                conn.Close();
            }
        }
    }
}

Console.WriteLine("databack with {0} columes", reader[0]); 中使用了序数索引器从数据库中检索列数据。

同时可以使用列名索引器(优点:使用列名索引器可以屏蔽由于添加删除列导致的列顺序变化,而产生的异常)

reader["CompanyName"].Tostring().PadLeft(25);

reader["ContactName"].Tostring().PadLeft(20);

然后如果知道了返回值的类型 还可以使用类型访问器

这个需要查表将数据库中定义的类型对用.NET Framework中的类型访问器

while(reader.Read())

{

Console.WriteLine("{0}\t{1}\t{2}\t{3}",reader.GetString(0).PadRight(30), reader.GetDecimal(1),reader.GetInt16(2),reader.GetBoolean(3));

}

类型访问器方法都以Get开头,用序数进行数据索引,是类型安全的

数据读取器的元数据属性和函数

函数或属性名称

说明

Depth

该属性表示当前行的嵌套深度

FieldCount

该属性表示结果集中的列数

GetDataTypeName

这个方法接收索引,返回含有列数据类型名称的字符串

GetfieldType

这个方法接收索引,返回对象的.NET FrameWork 数据类型

GetName

这个方法接收索引,返回指定列的名称

GetOrdinal

这个方法接收列名,返回列的索引

  Console.WriteLine("'{0|' is at index{1}" +
                        "and its type is:{2}",
                        reader.GetName(0),
                        reader.GetOrdinal("contactname"),
                        reader.GetFieldType(0));

获取表的数据

DataTable schema=reader.GetSchemaTable();

使用拼接的方式 使用数据读取器处理多个结果集

string sql1 = @“select companyname,contactname from customers where companyname like 'A%'";

string sql2 =@"select firstname,lastname from employees";

string sql=sql1+sql2;

SqlDataReader reader= cmd.executeReader();

do

{

while(reader.Read())

{

Console.WriteLine("".PadLeft(60,'='));

}

}

while(reader.NextResult());

抱歉!评论已关闭.