【问题标题】:mysql c# search textboxmysql c#搜索文本框
【发布时间】:2021-07-04 13:26:00
【问题描述】:

您好,我正在尝试从数据库中搜索产品名称并在我的文本框中显示我,但同时我需要该产品的 id 将其插入到网格中,然后插入到另一个表中。

MySqlConnection connection = new MySqlConnection("connectonString");

            string selectQuery = "select descricao,codigo from produtos where (barras = '@barcodes') or(descricao like '%' + @product + '%')";
            connection.Open();
            MySqlCommand command = new MySqlCommand(selectQuery, connection);
            MySqlDataReader reader = command.ExecuteReader();
            command.Parameters.AddWithValue("@barras", Txtcodigo.Text);
            command.Parameters.AddWithValue("@product", Txtcodigo.Text);
            //MySqlDataReader reader = command.ExecuteReader();
            DataTable dt2 = new DataTable();
            dt2.Load(reader);
            DataView dvDataTable = new DataView(dt2);
            //DataRow row = dt2.Rows[1];
            Txtproduto.Text = reader.GetString("descricao");

它说我的阅读器是空的,但是我使用相同的代码来加载组合框并且它可以工作,唯一的区别是在组合框上我的选择是:select * from unidades;并且没有参数,因为该表上只有 2 行,而 products 表上还有更多,我只需要那些 2:描述和 id;条形码只是为了搜索

【问题讨论】:

  • 您在将参数添加到查询之前调用了 ExecuteReader。
  • 同样在查询中,您将@barcodes 参数括在单引号中,这似乎是错误的

标签: c# mysql


【解决方案1】:

除了可能通过连接字符串进行 SQL 注入之外,使用现有的参数非常接近。

您的查询字符串有 (barras = '@barcodes'),去掉单个“引号”,您的参数应该是“条形码”,而不是 barras。至于带有“%”通配符的产品,创建一个强制整个参数默认包含它们的字符串......就像

string selectQuery = 
@"select 
      descricao,
      codigo 
   from 
      produtos 
   where 
          barras = @barcodes 
      or descricao like @product";

MySqlCommand command = new MySqlCommand(selectQuery, connection);
// the "@" is not required for the parameter NAMEs below, jut the string
// name of the parameter as in the query.

// Ok to use the actual text from your textbox entry here
command.Parameters.AddWithValue("barcodes", Txtcodigo.Text);

// but use the STRING created with '%' before/after created above
string parmProduct = '%' + Txtcodigo.Text.Trim() + '%';
command.Parameters.AddWithValue("product", parmProduct);

// NOW you can execute the reader and pull your data
connection.Open();
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
DataView dvDataTable = new DataView(dt2);
Txtproduto.Text = reader.GetString("descricao");

【讨论】:

  • 遇到了同样的错误,但我设法通过 descicao 删除产品搜索来使其工作,只对它们进行条形码返回产品描述,但我需要搜索机器人栏和描述
  • string selectQuery = "select descricao,codigo from produtos where barras =" + (Txtproduto.Text);连接.打开(); MySqlCommand command = new MySqlCommand(selectQuery, connection); MySqlDataReader reader = command.ExecuteReader(); if(reader.Read()) { Txtproduto.Text = reader.GetString("descricao"); Txtcodigopro.Text = reader.GetString("codigo"); }这有效,但仅适用于条形码搜索
猜你喜欢
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 2012-10-06
  • 1970-01-01
  • 2018-02-05
  • 1970-01-01
  • 1970-01-01
  • 2016-11-23
相关资源
最近更新 更多