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

qpgpyjmq  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(259)

启动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

我需要传递数据库表名作为变量,这会导致问题。我有一个窗体,当我传递给该窗体时,表名form show data for defined tabe in property。
检查我的代码:public partial class form1:form{private datatable dt;私有源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();
    }
}
643ylb08

643ylb081#

问题是事件的顺序。假设您的代码正在执行 form.DatabaseTableName = "products"; 在运行sql之前的行,但它不是。您的代码正在窗体构造函数中运行,这意味着 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();
}

相关问题