0

For now I execute a search in database and display the result with

string keyWord = textBoxSearch.Text.ToString();
using (SqlConnection con = new SqlConnection(conString))
{
    try
    {
        con.Open();
        if (con.State == ConnectionState.Open)
        {
            using (SqlCommand cmd = new SqlCommand("SELECT articleCode, articleName FROM Article WHERE articleName LIKE '" + keyWord + "%'", con))
            {
                // Put search result in dataGrid
            }
        }
    }
}

Now following SqlCommand.Parameters example I should do something like

string cmdQuery = "SELECT articleCode, articleName from Article WHERE articleName LIKE @articleName'";
using (SqlConnection con = new SqlConnection(conString))
{
    using (SqlCommand cmd = new SqlCommand(cmdQuery, con))
    {
        cmd.Parameters.Add("@articleName", SqlDbType.NVarChar);
        cmd.Parameters["@articleName"].Value = textBoxSearch.Text;
        try
        {
            // Put search result in dataGrid
        }
    }
}

But I don't really see how different this is because I still have to use the raw textBoxSearch.Text value. Am I doing this right ?

A. Petit
  • 158
  • 3
  • 14
  • 1
    Hi, look at this (similar) question: https://stackoverflow.com/questions/7174792/does-using-parameterized-sqlcommand-make-my-program-immune-to-sql-injection – richej Mar 08 '18 at 09:24
  • 1
    _"But I don't really see how different this is"_ then you should also read the text instead of just c&p the example codes ... ;D – Fildor Mar 08 '18 at 09:25
  • But seriously: I think your parameter name does not match the parameter in your query. It should, though AFAIK – Fildor Mar 08 '18 at 09:31
  • @Fildor I changed some names in my post because most of them were not in english. Looks like I missed some. – A. Petit Mar 08 '18 at 09:35

1 Answers1

0

To protect a web site from SQL injection, you can use SQL parameters. SQL parameters are values that are added to an SQL query at execution time, in a controlled manner.

Example:

txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();

The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally, and not as part of the SQL to be executed.

View this for more details.

And yes, you can still use the textbox to take in value.

King of the North
  • 393
  • 1
  • 5
  • 19