What should you do?

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application.
The application contains the following code segment. (Line numbers are included for reference only.)

01 class DataAccessLayer
02 {
03 private static string connString;
04 …
05 …
06 public static DataTable GetDataTable(string command){
07 …
08 …
09 }
10 }

You need to define the connection life cycle of the DataAccessLayer class.
You also need to ensure that the application uses the minimum number of connections to the database.
What should you do?

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to create an application.
The application contains the following code segment. (Line numbers are included for reference only.)

01 class DataAccessLayer
02 {
03 private static string connString;
04 …
05 …
06 public static DataTable GetDataTable(string command){
07 …
08 …
09 }
10 }

You need to define the connection life cycle of the DataAccessLayer class.
You also need to ensure that the application uses the minimum number of connections to the database.
What should you do?

A.
Insert the following code segment at line 04.
private static SqlConnection conn = new SqlConnection(connString);
public static void Open()
{
conn.Open();
}
public static void Close()
{
conn.Close();
}

B.
Insert the following code segment at line 04.
private SqlConnection conn = new SqlConnection(connString);
public void Open()
{
conn.Open();
}
public void Close()
{
conn.Close();
}

C.
Replace line 01 with the following code segment.
class DataAccessLayer : IDisposable
Insert the following code segment to line 04.
private SqlConnection conn = new SqlConnection(connString);
public void Open()
{
conn.Open();
}
public void Dispose()
{
conn.Close();
}

D.
Insert the following code segment at line 07:
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
}

Explanation:
One thing you should always do is to make sure your connections are always opened within a using statement.

Using statements will ensure that even if your application raises an exception while the connection is open, it will always be closed
(returned to the pool) before your request is complete. This is very important, otherwise there could be connection leaks.



Leave a Reply 0

Your email address will not be published. Required fields are marked *