I am trying to use some parameters in my sql query like this;
Answer_table = new MySqlParameter("@answerTable", AT);
MySqlCommand solved_q = new MySqlCommand("SELECT * FROM @answerTable WHERE UserID = @uID", c2.get_con());
solved_q.Parameters.Add(Answer_table);
solved_q.Parameters.Add(uID);
but It’s not working as I expected. It works for uID when I dont use a parameter for table name(@answerTable), is it because it is not allowed? if it is is there any other way to do that?
any help would be appreciated 🙂
It’s not allowed, because it’s part of the information the DBMS needs in order to compile its execution path for a prepared statement.
You would have to build the statement as a string at runtime, before you prepare it. Fortunately, most DBMS would still cache your prepared statemtent.
Important caveat: if the name of the table comes “from the outside” in any way (e.g. a parameter in a HTML request), you will have to be very careful to avoid SQL injection (i.e.: someone could pass something evil like “table1 ; drop table table1” instead of what you expect, and that would change the meaning of your SQL statement in unexpected ways).