如何通过一个表作为参数的MySqlCommand?参数、MySqlCommand

2023-09-04 00:22:33 作者:骨心一起醉碎

我创建一个方法,通过传递一个搜索栏来选择任何表的ID。

I am creating a method to select the id from any table by passing a search field.

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。当我看到异常消息,它显示我的报价表的查询! 我如何通过表作为参数不含引号?

But I get an MySqlException about syntax error. When i look at the Exception message, it shows me the query with the quoted table! How do I pass the table as parameter without quotes?

推荐答案

大多数数据库不会让你通过参数指定的表或列名。参数,目的是要为值的。如果你真的,真的需要这是动态的,你应该验证输入(它应该是一个已知的表名,与该表中的已知列名),然后包括在SQL。

Most databases won't let you specify table or column names via parameters. Parameters are meant to be for values. If you really, really need this to be dynamic, you should validate the input (it should be a known table name, with known column names within that table) and then include that in the SQL.

 
精彩推荐