如何通过一个表作为参数的MySqlCommand? [英] How to pass a table as parameter to MySqlCommand?

查看:160
本文介绍了如何通过一个表作为参数的MySqlCommand?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个方法,通过传递一个搜索栏来选择任何表的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.

这篇关于如何通过一个表作为参数的MySqlCommand?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆