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

时间:2018-01-09 12:34:44

标签: c# mysql

当我启动winforms c#app时出现此错误:

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:表格     {         私有DataTable dt;         private BindingSource bs;

    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;
}

当我手动输入GetData("SELECT * FROM products")时,所有工作都很好。但是当我从变量或属性传递表名时,我得到错误。

更新

public partial class MainWindow : Form
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void listaKupacaToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form1 form = new Form1();

        form.DatabaseTableName = "products";

        form.ShowDialog();
    }
}

1 个答案:

答案 0 :(得分:3)

问题在于事件的顺序。您假设您的代码在运行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();
}