Dynamic SQL with C# SqlCommand

痞子三分冷 提交于 2021-01-29 04:46:12

问题


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 selectint 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!