mysql c#搜索文本框



嗨,我正在尝试从数据库中搜索产品名称并在文本框中显示我,但同时我需要该产品的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");

它说我的阅读器是空的,但我使用了相同的代码来加载combobox,它有效,唯一的区别是在combobox上我的选择是:从unidades中选择*;没有参数,因为那个表上只有2行,而products表上有更多,我只需要那2行:description和id;条形码只是为了搜索

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

您的查询字符串有(barras='@barcodes'(,去掉单个"引号",您的参数应该是;条形码";,不是巴拉斯。至于您的产品"通配符,创建一个字符串,强制整个参数默认包含它们。。。像

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");

最新更新