【问题标题】:Datagrid view not populating when mysql parameters are used使用 mysql 参数时未填充 Datagrid 视图
【发布时间】:2018-10-09 20:54:52
【问题描述】:

我的想法是问题出在适配器上。但是,我仍然很年轻,希望能得到任何帮助。我搜索了这个论坛,但我发现的任何解决方案都没有运气(可能是pebkac)。该应用程序很简单,在参数化选择语句中使用文本框输入来填充数据网格视图。查询将执行,但网格保持为空。 VS2017,MySql8.0

private void button2_Click(object sender, EventArgs e)
    {
        string myConnectionstring = null;
        string mySelect = "SELECT * FROM part_data WHERE 'SERIAL' = @test; ";
        string tb7 = textBox7.Text;
        //Set Connection String And Create Connection
        myConnectionstring = "server=localhost;user= admin; database= trace;port=3306;password= admin;Allow User Variables=True";

        DataSet ds = new DataSet();

        using (MySqlConnection myConnection = new MySqlConnection(myConnectionstring))
        {   //Create Command Object
            //MySqlCommand myCommand = new MySqlCommand(mySelect, myConnection);



            try
            {
                myConnection.Open();
               // myCommand.Prepare();
                //myCommand.Parameters.AddWithValue("@test",tb7);
                MySqlDataAdapter adapter = new MySqlDataAdapter(mySelect, myConnectionstring);
                adapter.SelectCommand.Parameters.AddWithValue("@test",tb7);
                //debug to see final select statement
                richTextBox1.Text = mySelect;


                adapter.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            { 
                MessageBox.Show("Query Failed" + ex);
            }


        }

【问题讨论】:

    标签: c# mysql datagridview parameters


    【解决方案1】:

    乍一看,您的查询似乎很糟糕。尝试在列名周围使用反引号。

    SELECT * FROM part_data WHERE `SERIAL` = @test; 
    

    【讨论】:

    • 我相信SERIAL 是一个关键字。他可能需要使用反引号(`)
    • 抱歉,SERIAL 是列名。我只是尝试了反引号,它起作用了。这是一个小型测试应用,在我修改实际应用之前帮助实现参数。
    【解决方案2】:

    尝试不带参数的查询,没有必要那样做,然后尝试数据集的DataSourceView。

    【讨论】:

      猜你喜欢
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      相关资源
      最近更新 更多