Using C# SQL Parameterization on Column Names

后端 未结 3 889
再見小時候
再見小時候 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:41

    I have figured out a way to include a work around for parametrized column names. I had the same problem but came up with a different way and since I would be the only one using the column names then I believe this is still a safe bet.

                String sqlcomm = "SELECT * FROM Asset WHERE " + assetColName + " = ";
                command.CommandText = sqlcomm + "$assetColValue";
    
                //command.CommandText = @"SELECT * FROM Asset WHERE $assetColName = '$assetColValue'";
                //command.Parameters.AddWithValue("$assetColName", assetColName);
    
                command.Parameters.AddWithValue("$assetColValue", assetColValue);
    

    As you can see from the code above. I tried almost what you did which I then had to comment out. I then concatenated strings together and was able to use my paramterized column name and value which then the value is securely added. The column name however is not secured but this is a method that only I will be using so its still somewhat safe. You can add regular expressions if you want to be more secure but you get the idea of the fix.

提交回复
热议问题