数据读取器---处理多个结果集

有时想快点完成工作,同时使用两个或者多个查询,但又不想让应用程序的整体性能受到影响,如实例化多个命令或数据读取器对象,或者在代码中多次使用相同的对象,增大代码量。

数据读取器提供了这样一个方法:NextResult(),可以把读取器移到下一结果集。

示例:处理多个结果集

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace MultipleResults
{
    class Program
    {
        static void Main(string[] args)
        {
            string connString = @"
            server = .;
            integrated security =true;
            database =northwind";
            string sql1 = @"select companyname,contactname from customers where companyname like 'A%'";
            string sql2 = @"select firstname,lastname from employees";

            string sql = sql1 + sql2;
            SqlConnection conn = new SqlConnection(connString);

            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataReader rdr = cmd.ExecuteReader();
                do
                {
                    while (rdr.Read())
                    {
                        Console.WriteLine("{0} : {1}", rdr[0], rdr[1]);
                    }
                    Console.WriteLine("".PadLeft(60, '='));
                } while (rdr.NextResult());
                rdr.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error Occurred: " + e);
            }
            finally
            {
                conn.Close();
            }
            Console.ReadKey();
        }
    }
}

示例说明:

string sql=sql1 + sql2;

警告:某些DBMS要求在多个查询之间使用显式的分隔符,但SQL Server只要求在后续SELECT关键字的前面加上空白,上述字符串就符合这一要求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值