HI
I have a web service that fetches image names matching user input text in an autocomplete text box. The code below works but has a flaw - the SearchText is user input and I want to avoid SQL injection attacks.
List<string> my_list = new List<string>();
string conString = ConfigurationManager.ConnectionStrings["Images_Connection"].ConnectionString;
string query = "Select TOP (@Count) image_Name FROM dbo.Table_Images WHERE (image_Name LIKE '%@SearchText%')";
query = query.Replace("@Count", count.ToString());
query = query.Replace("@SearchText", prefixText);
SqlConnection sqlConn = new SqlConnection(conString);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
sqlConn.Close();
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
my_list.Add(row[0].ToString());
}
}
return my_list;
If I update the code to update the parameter @SearchText (as follows), even though I enter the same text, nothing is returned.
string query = "Select TOP (@Count) image_Name FROM dbo.Table_Images WHERE (image_Name LIKE '%@SearchText%')";
query = query.Replace("@Count", count.ToString());
SqlConnection sqlConn = new SqlConnection(conString);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
//https://forums.asp.net/t/1132244.aspx
cmd.Parameters.AddWithValue("@SearchText", prefixText);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
sqlConn.Close();
What am I doing incorrectly?
Thanks for any help.