如何将表作为参数传递给MySqlCommand?

我正在创建一个方法,通过传递搜索字段从任何表中选择id。

private int SelectId(string tabela, string campo, string valor) { int id = 0; using (command = new MySqlCommand()) { command.Connection = conn; command.Parameters.Add("@tabela", MySqlDbType.).Value = tabela; command.Parameters.Add("@campo", MySqlDbType.Text).Value = campo; command.Parameters.Add("@valor", MySqlDbType.VarChar).Value = valor; command.CommandText = "SELECT `id` FROM @tabela WHERE @campo=@valor;"; try { id = (int)command.ExecuteScalar(); } catch (MySqlException ex) { MessageBox.Show(ex.Number + " : " + ex.Message + command.CommandText); } catch (Exception) { throw; } } return id; } 

但我得到一个关于语法错误的MySqlException。 当我查看Exception消息时,它会显示带引号表的查询! 如何在没有引号的情况下将表作为参数传递?

大多数数据库都不允许您通过参数指定表名或列名。 参数适用于 。 如果你真的,真的需要它是动态的,你应该validation输入(它应该是一个已知的表名,在该表中有已知的列名),然后在SQL中包含它。

我同意乔恩。 下面是代码示例,其中表名直接插入到脚本中,而不是作为参数。 请注意,您仍然需要validation表和列名以防止SQL注入 。 我没有在这里包括,但我已经为你添加了注释存根。

 private int SelectId(string tabela, string campo, string valor) { int id = 0; using (command = new MySqlCommand()) { command.Connection = conn; command.Parameters.Add("@campo", MySqlDbType.Text).Value = campo; command.Parameters.Add("@valor", MySqlDbType.VarChar).Value = valor; // TODO: Validate table name for parameter 'tabela' to prevent SQL injection // TODO: Validate column name for parameter 'campo' to prevent SQL injection command.CommandText = "SELECT `id` FROM " + tabela + " WHERE @campo=@valor;"; try { id = (int)command.ExecuteScalar(); } catch (MySqlException ex) { MessageBox.Show(ex.Number + " : " + ex.Message + command.CommandText); } catch (Exception) { throw; } } return id; }