C# C数据库表名作为变量返回SQL语法错误

C# C数据库表名作为变量返回SQL语法错误,c#,mysql,C#,Mysql,启动winforms c应用程序时出现以下错误: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near at line 1 我需要将数据库表名作为变量传递,这会导致问题。 我有一个表单,当我传递给该表单表名时,表单显示属性中定义的tabe的数据 检查我的代码我做什么: 公共部分类Fo

启动winforms c应用程序时出现以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near at line 1
我需要将数据库表名作为变量传递,这会导致问题。 我有一个表单,当我传递给该表单表名时,表单显示属性中定义的tabe的数据

检查我的代码我做什么: 公共部分类Form1:Form { 专用数据表dt; 私有源绑定

    public string DatabaseTableName
    {
        get;
        set;
    }
    public Form1()
    {
        InitializeComponent();

        bs = new BindingSource();

        this.PopulateDataGridView();
    }

private void PopulateDataGridView()
{

    string query = String.Format("SELECT * FROM {0}", DatabaseTableName);

    DataTable data = GetData(query); // ERROR is HERE

    bs.DataSource = data;

    dataGridView1.DataSource = bs;
    bindingNavigator1.BindingSource = bs;
}



private DataTable GetData(string q)
{
    using (var conn = new MySqlConnection(Db.connStr))
    {
        try
        {
            conn.Open();

            using (MySqlDataAdapter adapter = new MySqlDataAdapter(q, conn))
            {
                dt = new DataTable();
                adapter.Fill(dt);

                return dt;
            }
        }
        catch (MySqlException e)
        {
            MessageBox.Show(e.Message);
        }
    }

    return dt;
}
当我手动输入产品中的GetDataSELECT*时,一切正常。但当我从变量或属性中传递表名时,我得到了错误

更新:


问题是事件的顺序。假设代码在运行SQL之前执行form.DatabaseTableName=products;行,但实际上不是。代码在表单构造函数中运行,这意味着尚未设置DatabaseTableName变量

一个简单的修复方法是在构造函数中传入值,例如:

public Form1(string tableName)
{
    InitializeComponent();

    bs = new BindingSource();

    //Set it here
    this.DatabaseTableName = tableName;

    this.PopulateDataGridView();
}
现在,当您创建表单时:

private void listaKupacaToolStripMenuItem_Click(object sender, EventArgs e)
{
    Form1 form = new Form1("products");
    form.ShowDialog();
}

那么这里DatabaseTableName的内容是什么?您正在生成的SQL查询是什么?而且,这对SQL注入非常开放。DatabaseTableName的值是什么?它的数据库表名form.DatabaseTableName=products;在哪里调用?您确定要调用它吗?您的查询在构造函数中运行。在const执行器运行,您分配DatabaseTableName。太晚了。
private void listaKupacaToolStripMenuItem_Click(object sender, EventArgs e)
{
    Form1 form = new Form1("products");
    form.ShowDialog();
}