I have been working on an old project recently. I found in the project that previous colleagues have created some common methods to use for to open connection to database. But I have a doubt about the process whether it really handles connection by IDispose once the query completes.
Here is the methods:
Connect database.
/// <summary>
/// This method creates a connection object to the database.
/// </summary>
/// <returns>a new SQL Connection</returns>
public SqlConnection ConnectDB()
{
var db = new SqlConnection(ConnectionString);
db.Open();
return db;
}
public SqlDataReader GetDataReader(SqlCommand query)
{
var db = ConnectDB();
query.Connection = db;
var reader = query.ExecuteReader();
return reader;
}
Then we use GetDataReader as below
var queryProduct= new SqlCommand
{
CommandText = "SELECT DISTINCT ProductName FROM Products"
};
using (var reader = Interaction.GetDataReader(queryProduct))
{
while (reader.Read())
{
var b = new Product
{
ProductName = reader.GetString(reader.GetOrdinal("ProductName"))
};
products.Add(b);
}
}
Do you think this process would release all the connection correctly?
The code isn't safe. Disposing/closing the reader doesn't automatically close the connection, as you may want to execute multiple commands on the same connection. Even if you use the override that does close the connection, exceptions that may occur before you enter the
using
block will leave the connection open.The typical way is to wrap the connection, command and reader in
using
statements: