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

后端 未结 4 1880
长情又很酷
长情又很酷 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:06

    You can put (and should!) parameters into your SQL queries for the values in e.g. your WHERE clause - but you cannot parametrize stuff like your table name.

    So I'd rewrite that query to be:

    SELECT (list of columns)
    FROM dbo.Actor
    WHERE ActorName = @ActorName
    

    and then pass in just the value for @ActorName.

    If you need to do the same thing for directors, you'd have to have a second query

    SELECT (list of columns)
    FROM dbo.Directors
    WHERE DirectorName = @DirectorName
    

    Using parameters like this

    • enhances security (prohibits SQL injection attacks!)
    • enhances performance: the query plan for that query can be cached and reused for second, third runs

    PS: the original problem in your setup is this: you don't have any space between the first occurence of your table name and the WHERE clause - thus you would get:

    SELECT * FROM ActorWHERE ActorName ='.....'
    

    If you really insist on concatenating together your SQL statement (I would NOT recommend it!), then you need to put a space between your table name and your WHERE !

    Update: some resources for learning about parametrized queries in ADO.NET:

    • The C# Station ADO.NET Tutorial / Lesson 06: Adding Parameters to Commands
    • Using Parameterized Queries with the SqlDataSource

提交回复
热议问题