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?

beefoak
  • 136
  • 1
  • 10
  • 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.) – Jeroen Mostert Sep 12 '18 at 15:41
  • I see. Thank you! – beefoak Sep 12 '18 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. – juharr Sep 12 '18 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. – Sergey Kalinichenko Sep 12 '18 at 15:54

1 Answers1

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);
        }
    }