Which code segment should you insert at the line 04?

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

01 public static SqlDataReader GetDataReader(string sql)
02 {
03 SqlDataReader dr = null;
04 …
05 return dr;
06 }

You need to ensure that the following requirements are met:
* The SqlDataReader returned by the GetDataReader method can be used to retreive rows from the database.
* SQL connections opened within the GetDataReader method will close when the SqlDataReader is closed.

Which code segment should you insert at the line 04?

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

01 public static SqlDataReader GetDataReader(string sql)
02 {
03 SqlDataReader dr = null;
04 …
05 return dr;
06 }

You need to ensure that the following requirements are met:
* The SqlDataReader returned by the GetDataReader method can be used to retreive rows from the database.
* SQL connections opened within the GetDataReader method will close when the SqlDataReader is closed.

Which code segment should you insert at the line 04?

A.
using(SqlConnection cnn = new SqlConnection(strCnn))
{
try
{
SqlCommand cmd = new SqlCommand(sql, cnn);
cnn.Open();
dr = cmd.ExecuteReader();
}
catch
{
throw;
}
}

B.
SqlConnection cnn = new SqlConnection(strCnn);
SqlCommand cmd = new SqlCommand(sql, cnn);
cnn.Open();
{
try
{
dr = cmd.ExecuteReader();
}
finally
{
cnn.Close();
}
}

C.
SqlConnection cnn = new SqlConnection(strCnn);
SqlCommand cmd = new SqlCommand(sql, cnn);
cnn.Open();
{
try
{
dr = cmd.ExecuteReader();
cnn.Close();
}
catch
{
throw;
}
}

D.
SqlConnection cnn = new SqlConnection(strCnn);
SqlCommand cmd = new SqlCommand(sql, cnn);
cnn.Open();
{
try
{
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch
{
cnn.Close();
throw;
}
}

Explanation:
CommandBehavior.CloseConnection When the command is executed, the associated Connection object is closed
when the associated DataReader object is closed.

CommandBehavior Enumeration
(http://msdn.microsoft.com/en-us/library/system.data.commandbehavior.aspx)

SqlCommand.ExecuteReader Method (CommandBehavior)
(http://msdn.microsoft.com/en-us/library/y6wy5a0f.aspx)



Leave a Reply 0

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