Articles → CSHARP → Using Statement In C#
Using Statement In C#
Purpose
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand(commandString, connection);
connection.Open();
reader = cmd.ExecuteReader();
while (reader.Read()) {
listBox1.Items.Add(reader[0].ToString() + ", " + reader[1].ToString());
}
reader.Close();
connection.Close();
reader.Close();
connection.Close();
- Use the Try-Catch-Finally block and close Datareader and connection in the Finally block
- Use the "using" statement to ensure that the Datareader and connection object will be closed before exiting the loop
Using Statement In Action
using(SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand cmd = new SqlCommand(commandString, connection);
connection.Open();
using(SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
listBox1.Items.Add(reader[0].ToString() + ", " + reader[1].ToString());
}
}
}