Which of the following two examples are correct? (Or which one is better and should I use)
In the MSDN I found this:
private static void ReadOrderData(string connectionString) { string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;" using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); // Call Read before accessing data. while (reader.Read()) { Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); } // Call Close when done reading. reader.Close(); } }
However looking other pages some users suggest to do it this way:
private static void ReadOrderData(string connectionString) { string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = new SqlCommand(queryString, connection)) { connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { // Call Read before accessing data. while (reader.Read()) { Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); } } } } }
So, the question is: should I use the using
statement also in the SqlCommand
and in the SqlDataReader
or they are automatically disposed at the end of the SqlConnection
using
code block.
You must ensure the Close method is called when you are through using the SqlDataReader before using the associated SqlConnection for any other purpose. The Close method may either be called directly or through the Dispose method, disposing directly or in the context of the using statement block.
The SqlDataReader is used to read a row of record at a time which is got using SqlCommand. It is read only, which means we can only read the record; it can not be edited. And also it is forward only, which means you can not go back to a previous row (record).
ADO.NET SqlDataReader Class. This class is used to read data from SQL Server database. It reads data in forward-only stream of rows from a SQL Server database. it is sealed class so that cannot be inherited.
As explained earlier, the SqlDataReader returns data via a sequential stream. To read this data, you must pull data from a table row-by-row Once a row has been read, the previous row is no longer available.
The second option means your reader
will be closed in the event of an exception after it has been created, so it is preferred.
It is effectively transformed by the compiler to:
SqlDataReader reader = command.ExecuteReader(); try { .... } finally { if (reader != null) ((IDisposable)reader).Dispose(); }
See MSDN for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With