0

I'm working on a simple script to query a database based off user input, and I was wondering if there's any chance of injection with something like .net's parameterized queries?

4
  • 5
    Assuming no plain strings are interjected and you fire off only constants with the parameter names in them, there's no chance of injection. That's more or less why the use of parameters is so heavily encouraged. (Well, they have other benefits, like plan reuse, but that's another story.) Commented Sep 12, 2018 at 15:41
  • I see. Thank you! Commented Sep 12, 2018 at 15:42
  • 1
    You could also use a ORM like EF. Or at the very least I'd suggest using Dapper to avoid a lot of the ADO.Net boilerplate code. Commented Sep 12, 2018 at 15:50
  • 1
    There is no chance of SQL injection with fully parameterized SQL queries. .NET libraries transfer parameter values to SQL Server in a way that prevents their re-interpretation as SQL comments or keywords. Unfortunately, it does not make you 100% safe. You need to avoid certain constructs that open your system up for injection attacks - specifically, you need to avoid calling EXEC directly. Commented Sep 12, 2018 at 15:54

1 Answer 1

1

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from Here:

 private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.