Click here to Skip to main content
15,919,178 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following code, should I have two datareaders or I can reuse this object after having closed it?

C#
searchCommand = "SELECT * FROM titles WHERE titles.KEY=@EKEY";
               linkCommand.CommandText = searchCommand;
               linkCommand.Prepare();
               linkCommand.Parameters.AddWithValue("@EKEY", EKEY);

               linkReader = linkCommand.ExecuteReader();
               linkCommand.Parameters.Clear();

               while (linkReader.Read())
               {
                   //some logic here
               }
               linkReader.Close();
               WriteLog("done authors");


               searchCommand = "SELECT * FROM pros WHERE pros.EKEY=@EKEY";
               linkCommand.CommandText = searchCommand;
               linkCommand.Prepare();
               linkCommand.Parameters.AddWithValue("@EKEY", EKEY);

               linkReader = linkCommand.ExecuteReader();
               linkCommand.Parameters.Clear();

               while (linkReader.Read())
               {
                   //some logic here
               }
               linkReader.Close();
Posted

1 solution

No, you don't need to create another instance, once closed, just add another command to it and execute it again. You can reuse it, but make sure another command has been added to it.

Also, when you're working with Resources and Stream, use the Using syntax to work with them. Using the using () { } syntax, you will allow .NET framework to take care of the resources itself. Close, Dispose and Flush functions would be called where required and you won't have to worry about them at all.

http://msdn.microsoft.com/en-us/library/yh598w02.aspx[^]
 
Share this answer
 
Comments
Medise 19-Oct-14 15:30pm    
I have used the same command too, you mean I have to create another one or its enough to change the command text?
Afzaal Ahmad Zeeshan 19-Oct-14 15:37pm    
Just change the command text it will be enough.
Medise 19-Oct-14 15:39pm    
Thankyou so much.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900