Using C# SQL Parameterization on Column Names

后端 未结 3 884
再見小時候
再見小時候 2021-01-27 15:52

I\'m having a problem. I want this to work, but it doesn\'t:

SqlDataSource.SelectCommand = \"SELECT blah1, blah2 FROM myTable WHERE @ColumnName = @Value\";

SqlD         


        
3条回答
  •  生来不讨喜
    2021-01-27 16:51

    Since query parameters are resolved after the SQL is parsed and an execution plan is generated, you can't actually dynamically build SQL with parameters. I would recommend building the SQL string itself, in a safe way of course. Perhaps first create an enum of valid column names:

    enum DbColumns { One, Two, Three };
    

    And then build the SQL string like so:

    DbColumns colName = (DbColumns)Enum.Parse(typeof(DbColumns), "One");
    SqlDataSource.SelectCommand = String.Format("SELECT blah1, blah1 FROM myTable WHERE {0} = @Value", colName);
    

    Another idea would be to validate the column name using a regular expression, perhaps only allowing [a-z].

提交回复
热议问题