I'm trying to run the following snippet as Console app, and I get an error:
"a reader is already open for this connection, and should be closed first"
I tried to manually say:
SqlDataReader.Close() in the begining of the code, but still get the error, Any suggecstions how to manually close the reader?
thank you
---- here's the code ----
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace ADO.NET
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
SqlConnection cn = new SqlConnection
("SERVER=MyServer; INTEGRATED SECURITY=TRUE;" +
"DATABASE=AdventureWorks");
SqlCommand cmd1 = new SqlCommand ("Select * from HumanResources.Department", cn);
cmd1.CommandType = CommandType.Text;
try
{
cn.Open();
SqlDataReader rdr = cmd1.ExecuteReader();
while (rdr.Read())
{
if (rdr["Name"].ToString() == "Production")
{
SqlCommand cmd2 = new SqlCommand("SELECT * FROM "
+ "HumanResources.Employee WHERE DepartmentID = 7", cn);
cmd2.CommandType = CommandType.Text;
SqlDataReader rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
}
rdr2.Close();
}
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine
(ex.Message);
}
finally
{
cn.Close();
}
}
}
}
Only one reader at a time can be active on a single connection. Create a second connection and all will be well.
This is not a real problem, since connection pooling will make efficient use of connections.
|||thanks!
No comments:
Post a Comment