Variable table name using dynamic SQL in C#

后端 未结 4 1757
没有蜡笔的小新
没有蜡笔的小新 2020-12-21 19:06

I\'ve been looking around for a way to enter a variable table name and it seems the best way is to use dynamic sql, although it can lead to SQL injection. Can anyone demonst

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-21 19:45

    The simplest way is to simply use string concatenation to put the table name into your SQL query. However, you'd still be open to SQL injection as long as a malicious user can inject an arbitrary string into your query. For instance, let's say your API URL is http://example.org/all?table_name=customer&order=desc, and you are just extracting "table_name" from the URL for the user name.

    You should prevent possible SQL injections by having a static server side whitelist of valid table names (e.g. String[] ValidTableNames = new String[] { "customer", "purchase", ... }, and ensuring that the table_name param value is one of these values before adding it to your SQL query.

提交回复
热议问题