首页 > 解决方案 > 如何在 ASP.NET 中使用多个 SqlDataReader

问题描述

SqlDataReader在里面使用connection1,我使用另一个SqlDataReaderconnection2。所以连接打开问题发生连接1打开。如何解决?请提供解决方案

标签: asp.net

解决方案


  1. 首先创建不同的连接,datareader...对象
  2. 如果未读取数据,则关闭连接数据读取器

示例代码

string connectionString1 = "Data Source=localhost;Integrated security=SSPI;Initial Catalog=AdventureWorks;";
string connectionString2 = "Data Source=localhost;Integrated security=SSPI;Initial Catalog=AdventureWorks;";
//Create the command 
string sqlSelect1 = "SELECT TOP 5 CustomerID, AccountNumber FROM Sales.Customer";
string sqlSelect2 = "SELECT TOP 5 CustomerID, AccountNumber FROM Sales.Customer";
//open the connection
SqlConnection objConn1 = new SqlConnection(connectionString1);
SqlConnection objConn2 = new SqlConnection(connectionString2);
// Create the command and open the connection
SqlCommand objcommand1 = new SqlCommand(sqlSelect1, objConn1);
SqlCommand objcommand2 = new SqlCommand(sqlSelect2, objConn2);
objConn1.Open();
objConn2.Open();
// Create the DataReader to retrieve data
SqlDataReader DR1 = objcommand1.ExecuteReader())
SqlDataReader DR2 = objcommand2.ExecuteReader())
while (DR1.Read())
{
if(DR2.Read())
{
    //YOUR CODE
}
else
{
DR2.Close();
}
}
DR1.Close();
DR2.Close();
objConn1.Close();
objConn2.Close();

推荐阅读