Which code segment should you use?

You use Microsoft .NET Framework 4 to develop an application that connects to a Microsoft SQL
Server 2008 database. The application contains the following code segment.
string SQL = string.Format (“SELECT * FROM Customer WHERE CompanyName LIKE ‘%{0}%'”,
companyName);
var cmd = new SqlCommand(SQL, con);
You need to reduce the vulnerability to SQL injection attacks. Which code segment should you use?

You use Microsoft .NET Framework 4 to develop an application that connects to a Microsoft SQL
Server 2008 database. The application contains the following code segment.
string SQL = string.Format (“SELECT * FROM Customer WHERE CompanyName LIKE ‘%{0}%'”,
companyName);
var cmd = new SqlCommand(SQL, con);
You need to reduce the vulnerability to SQL injection attacks. Which code segment should you use?

A.
string SQL = “SELECT * FROM Customer WHERE ” +
“CompanyName LIKE @companyName”;
var cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue(“@companyName”,
string.Format(“%{0}%”, companyName));

B.
string SQL = “SELECT * FROM Customer WHERE ” +
“CompanyName LIKE @companyName”;
var cmd = new SqlCommand(SQL, con);
var param = new SqlParameter(“@companyName”,
string.Format(“%{0}%”, companyName));

C.
string SQL = string.Format(“SELECT * FROM ” +
“Customer WHERE CompanyName LIKE {0}”,
new SqlParameter(“@companyName”,
string.Format(“%{0}%”, companyName)));
var cmd = new SqlCommand(SQL, con);

D.
string SQL = “SELECT * FROM Customer @companyName”;

var cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue(“@companyName”,
string.Format(“WHERE CompanyName LIKE ‘%{0}%'”,
companyName));

Explanation:
SqlParameterCollection.AddWithValue Method
(http://msdn.microsoft.com/enus/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx)



Leave a Reply 0

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