问题描述
我想用了MySQLParameter
通过tableName值进入查询(防止SLQ注射)
I want to use MySqlParameter
to pass tableName into query (to prevent slq injections)
MySqlCommand cmd = new MySqlCommand("select * from @table"), cn)
cmd.Parameters.AddWithValue("@table",TableName);
但是,这是行不通的。如何传递tableName值作为参数
But this is not working. How can I pass tableName as parameter
P.S。我试图改变 @
到
- ?不工作
P.S. I tried to change @
to ?
- not working
推荐答案
您无法通过表名作为参数。
你必须使用动态SQL来做到这一点,所以你必须字符串集中去做,例如:
You cannot pass table name as parameter.You have to use dynamic SQL to do this, so you have to string concentration to do it, for example
MySqlCommand cmd = new MySqlCommand(String.Format("select * from {0}",tableName), cn)
但由于用户输入了表名,所以SQL注入是可能的。您可以使用此SQL以确定是否表从中查询任何事情之前存在:
But because users input the tableName, so SQL injection is possible. You can use this SQL to determine if that table exists before query anything from it:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename';
(你可以完全参数化此查询,所以SQL注入将被淘汰)
(You can perfectly parametrize this query, so SQL injection will be eliminated)
一般情况下,要小心SQL注入。但是,如果你使用这个内部(不暴露给用户),那么SQL注入应该不是问题。
Generally, be careful of SQL injection. But if you use this internal (not expose to user), then SQL injection should not be problem.
更好,你可以构建一个存储过程来解决这个问题,因为在我的另一个答案:
Better, you can construct a stored procedure to deal with this, as in my another answer:
的
这篇关于作为了MySQLParameter表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!