I tried to find my answer on google as always but I found only a partial answer to my question.
My question is: while creating a connection to a database, what is the more preferable way to make it: without or with the USING
.
For now, as I start in C# (but I have some skill in PHP), I learned online with the USING
method like below:
string conString = Properties.Settings.Default.mattDatabaseConnectionString;
using (SqlCeConnection con = new SqlCeConnection(conString))
{
using (SqlCeCommand query = new SqlCeCommand("SELECT * FROM customers", con))
{
SqlCeDataReader reader = query.ExecuteReader();
}
}
On google, I found that the use of the USING prevent from forget to close the ExecuteReader
and dispose the SqlCeCommand
. But you can also make it without like below (example took from msdn):
SqlCeConnection conn = null;
SqlCeCommand cmd = null;
SqlCeDataReader rdr = null;
try
{
// Open the connection and create a SQL command
//
conn = new SqlCeConnection("Data Source = AdventureWorks.sdf");
conn.Open();
cmd = new SqlCeCommand("SELECT * FROM DimEmployee", conn);
rdr = cmd.ExecuteReader();
// Iterate through the results
//
while (rdr.Read())
{
int employeeID = rdr.GetInt32(0); // or: rdr["EmployeeKey"];
string lastName = rdr.GetString(5); // or: rdr["FirstName"];
}
// Always dispose data readers and commands as soon as practicable
//
rdr.Close();
cmd.Dispose();
}
finally
{
// Close the connection when no longer needed
//
conn.Close();
}
I know the 2 methods above are equivalent but whats is the best method for skilled programmers and why. Probably the second for less characters??
And is the SqlCeEonnection conn = null;
and the 2 others really necessary??
Thanks guys