在C#的ADO.Net中可以通过设置连接串的MultipleActiveResultSets属性为True
来允许一个SqlConnection中打开两个SqlDataReader
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace 一个连接可以打开多个SqlDataReader
{
class Program
{
static void Main(string[] args)
{
SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
sb.DataSource = "192.168.8.249";
sb.InitialCatalog = "PA";
sb.UserID = "sa";
sb.Password = "kicpassword";
sb.MultipleActiveResultSets = true; //通过这个属性设置一个连接可以打开多个DataReader
string _conStr = sb.ConnectionString;
string _sql = "SELECT TOP 10 BatchID,BatchNo,BoxNo,importTime FROM dbo.M_Batch01 where isreturn=0 order by BatchID";
using (SqlConnection _conn = new SqlConnection(_conStr))
{
using (SqlCommand _cmd = new SqlCommand(_sql, _conn))
{
_conn.Open();
using (SqlDataReader reader1 = _cmd.ExecuteReader())
{
if (reader1.HasRows)
{
while (reader1.Read())
{
for (int i = 0; i < reader1.FieldCount; i++)
{
Console.Write(reader1[i].ToString()+"\t");
}
Console.WriteLine();
//打开第二个Reader,必须要重新New一个SqlCommand
_sql = "SELECT TOP 10 * FROM dbo.D_ListBoxValues";
using (SqlCommand _cmd1 = new SqlCommand(_sql, _conn))
{
using (SqlDataReader reader2 = _cmd1.ExecuteReader())
{
if (reader1.HasRows)
{
while (reader2.Read())
{
for (int j = 0; j < reader2.FieldCount; j++)
{
Console.Write(reader2[j].ToString() + "\t");
}
Console.WriteLine();
}
}
}
}
}
}
}
}
}
Console.ReadLine();
}
}
}