gpt4 book ai didi

c# - MySqlParameter 作为表名

转载 作者:行者123 更新时间:2023-11-29 01:32:53 26 4
gpt4 key购买 nike

我想使用 MySqlParameter 将 tableName 传递到查询中(以防止 slq 注入(inject))

MySqlCommand cmd = new MySqlCommand("select * from @table"), cn)
cmd.Parameters.AddWithValue("@table",TableName);

但这行不通。如何将 tableName 作为参数传递

附言我试图将 @ 更改为 ? - 不起作用

最佳答案

您不能将表名作为参数传递。您必须使用动态 SQL 来执行此操作,因此您必须以字符串集中的方式执行此操作,例如

  MySqlCommand cmd = new MySqlCommand(String.Format("select * from {0}",tableName), cn)

但是因为用户输入了表名,所以SQL注入(inject)是可能的。您可以使用此 SQL 来确定该表是否存在,然后再从中查询任何内容:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename';

(您可以完美地参数化此查询,因此将消除 SQL 注入(inject))

一般要注意SQL注入(inject)。但是如果你使用这个内部(不暴露给用户),那么 SQL 注入(inject)应该不是问题。

更好的是,你可以构建一个存储过程来处理这个问题,就像我的另一个答案:

Unified SQL getter with LINQ

关于c# - MySqlParameter 作为表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com