我的应用程序中的mySQL查询有什么问题?

时间:2013-05-01 05:21:09

标签: c# mysql winforms

我有一个主窗体(formMain),它在load事件中加载用户控件(分类)。并且在用户控件分类的加载事件中,它显示数据网格视图。让我告诉你代码。 的分类

string serverstring = "user id = root; password=; server=localhost; database=purchase_order; connection timeout=3;";

        private void load_data() 
        {
            MySqlConnection con = new MySqlConnection(serverstring);

            try
            {
                string query = "SELECT * FROM tblclassification";

                MySqlCommand cmd = new MySqlCommand(query, con);
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);


                DataTable dt = new DataTable();
                da.Fill(dt);


                dataGridView1.DataSource = dt;
                dataGridView1.DataMember = dt.TableName;
            }
            catch (Exception)
            {


            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }    
        }

幸运的是它正在工作但是当我点击位于另一个用户控件(搜索)中的搜索按钮时,它会在主窗体(formMain)中引发一个事件,其中它必须在用户控件(分类)中过滤datagridview但我的代码不是工作。 也许我的字符串查询中有语法错误。这是代码。

主要表格

void SearchClicked(object sender, EventArgs e)
        {
            Search content = _searchbox;
            classification control = new classification();
            MySqlConnection con = new MySqlConnection(serverstring);


            try
            {                
                string query = "SELECT * FROM tblclassification WHERE class_name LIKE '%@search'";

                MySqlCommand cmd = new MySqlCommand(query, con);
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);


                //MessageBox.Show(content.txtboxSearch.Text);
                cmd.Parameters.AddWithValue("@search", content.txtboxSearch.Text);


                DataTable dt = new DataTable();
                da.Fill(dt);




                control.dataGridView1.DataSource = dt;
                control.dataGridView1.DataMember = dt.TableName;


            }
            catch (Exception)
            {

            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }    
        }

2 个答案:

答案 0 :(得分:2)

使用CONCAT()

string query = @"SELECT * 
                 FROM   tblclassification 
                 WHERE  class_name LIKE CONCAT('%', @search)";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("@search", content.txtboxSearch.Text);


MySqlDataAdapter da = new MySqlDataAdapter(cmd);

答案 1 :(得分:0)

“SELECT * FROM purchase_order.tblclassification WHERE class_name LIKE('%@ search%')”;

或..

“SELECT * FROM tblclassification WHERE(class_name LIKE'%@ search%')”