问题
I'd like to create a dynamic SQL query with c#'s SqlCommand
where even the table is a parameter, so as to avoid injection attempts. Like below:
comm.CommandText = "SELECT * FROM @tbl WHERE cond=@cond";
comm.Parameters.AddWithValue("tbl","TABLENAME");
comm.Parameters.AddWithValue("cond","CONDITION");
However, I have found that this is not allowed. I've looked into using Dynamic SQL with an execute, but that seems to be only for stored procedures. Can I use Dynamic SQL with an Execute using parameters for the table name with an SqlCommand? If not, how can this be done to avoid SQL injection problems?
Thanks!
回答1:
Use SqlCommandBuilder.QuoteIdentifier method to escape table names.
SqlCommandBuilder builder = new SqlCommandBuilder();
string tableName ="SomeTable";
string escapedTableName = builder.QuoteIdentifier(tableName);
Later you can use the escaped table name in your string like:
comm.CommandText = "SELECT * FROM "+ escapedTableName +" WHERE cond=@cond";
回答2:
If the name of the table you're select
int from is not user-supplied, there's nothing to worry about.
If, however, you allow dynamic specification of tables to be queried, you'll need the QuoteIdentifier
approach suggested by @Habib and I strongly recommend whitelisting all the available table names.
来源:https://stackoverflow.com/questions/24491996/dynamic-sql-with-c-sharp-sqlcommand