Search code examples
c#sql-injection

How to make dynamic database selection injection-proof in C# SQL


While trying make my code injection-proof, a previously functional area is now throwing an 'Invalid object name' error:

static void TestSQL(ref SqlConnection conn)
{
    var dataTable = new DataTable();

    // This line worked
    //var com = new SqlCommand("SELECT * FROM [" + GetDatabaseName() + "].[dbo].[LOCATION]", conn);

    // These throw an error
    var com = new SqlCommand("SELECT * FROM [@databaseName].[dbo].[LOCATION]", conn);
    com.Parameters.AddWithValue("@databaseName", GetDatabaseName());

    using (SqlDataAdapter adapter = new SqlDataAdapter(com))
    {
        adapter.Fill(dataTable); // -- Error occurs here --
    }
}

The exact message is

"Invalid object name '@databaseName.dbo.LOCATION'."

It seems that AddWithValue doesn't like substituting that database name, which was kind of the point of this query. Somehow none of the dozens of injection threads I've read address making the database dynamic.

How can I be both injection-proof AND maintain my requirement of dynamic database selection? Thanks in advance!


Solution

  • specify the database name when you create the connection and not in the SQL