Reputation: 1143
I am trying to learn the concepts of SQL injection and how to prevent them. I understand that parameterization can help with this. However, when applying it to my query it doesn't seem to work. Here is my code:
string query = "Select * from Database where ClientName = @ClientName";
using (SqlConnection sqlConn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
cmd.Parameters.Add("@ClientName", SqlDbType.VarChar).Value = ClientName;
sqlConn.Open();
using (SqlDataReader myReader = cmd.ExecuteReader())
{
dt.Load(myReader);
}
}
}
My query works if I hard code the client name in or if I run the query in SQL obviously. It just seems like it isn't accepting my parameter and that it is literally searching for "@ClientName"
Upvotes: 0
Views: 78
Reputation: 2012
You shouldn't need to add the sqlDbType like you do here..
cmd.Parameters.Add("@ClientName", SqlDbType.VarChar).Value = ClientName;
this should work..
cmd.Parameters.Add("@ClientName", ClientName);
Even then, you want to AddWithValue instead of add.. so like this. The Add is the old way of doing this.. I have actually never used it in any of my courses.
cmd.Parameters.AddWithValue("@ClientName", ClientName);
Upvotes: 1