问题
As a reaction to MySqlParameter as TableName, it seems that MySQL's Connector/NET library doesn't support table names from user input in the following way:
MySqlCommand cmd = new MySqlCommand("SELECT * FROM @table");
cmd.Parameters.AddWithValue("@table",TableNameFromUserInput);
So I tried to find another way, but I couldn't find any libraries that did this for me.
When searching for how to do this manually, I couldn't found anything that didn't tell you to use "prepared statements" from some already defined library, no matter the language.
To my limited knowledge of SQL, I only think it's necessary to put backticks (`) around the user input and then check the input for backticks - but I wanted to be sure.
Question
How do you protect a user specified table name from SQL-Injection when the MySQL Connector doesn't support it?
回答1:
Check if
TableNameFromUserInput
is an existing table, before executing the query. That prevents other errors like "table doesnt exist" aswell.
回答2:
you cannot add tableName
(as well as columnName) as parameter in prepared statements because it only supports for a value. For your safety, add additional code to validate tableName, ex.
string tableName = "hello";
tableName = UDFunctionClean(tableName);
string query = String.Format("SELECT * FROM `{0}`", tableName);
MySqlCommand cmd = new MySqlCommand(query);
来源:https://stackoverflow.com/questions/13495968/how-to-protect-user-specified-table-name-from-sql-injection-in-c-using-mysql