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

pro*_*mad 3 .net c# mysql

我正在创建一个方法,通过传递搜索字段从任何表中选择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;
}
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 6

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