Using variables in SQL queries in asp.net (C#)

后端 未结 4 1845
长情又很酷
长情又很酷 2021-01-05 13:47

I have an SQL query of this form

string cmdText = \"Select * from \" + searchTable 
  + \"WHERE \" + searchTable 
  + \"Name =\' \" +   searchValue + \"\'\";         


        
4条回答
  •  孤城傲影
    2021-01-05 14:14

    You shouldn't concatenate string to SQL, as this will open you up to SQL Injection attacks.

    This is a rather long read about dynamic SQL, but worth reading to understand the risks and options.

    You should be using parameterized queries instead, though the only way to use a table name as a parameter is to use dynamic SQL.

    I urge you to change your approach regarding table names - this will lead to problems in the future - it is not maintainable and as I mentioned above, could open you to SQL Injection.


    The error you are seeing is a result of the concatenation you are doing with the "Where " clause - you are missing a space before it. You are also adding a space after the ' in the parameter ending with "Name".

    Your resulting string, using your example would be:

    Select * from ActorWHERE ActorName =' some actor';
    

提交回复
热议问题