[英]No row was deleted/updated, error with SQL Server in C# (Winforms)
[英]SQL Server And C# WinForms error
我在窗体加载ivent GetProducts(“”);上调用此方法; 该查询在sql中工作正常。 直到我在其中添加调试器的地方,它才起作用>> SqlDataReader myReader = cmd.ExecuteReader(); 谁能给我一些建议?
public void GetProducts(string find)
{
try
{
using (SqlCommand cmd = new SqlCommand("SELECT ID, BarCode, ArtNumber, ProductName, Price, SelfPrice, PriceWithOutAWD, TotalSelfPrice, UnitsInStock, " +
" Comment, InputDateTime, InputQuantity, Margin, CategoryName, TypeName, ExpDate FROM GetProducts"+
"WHERE BarCode LIKE '%@F%' OR ArtNumber LIKE '%@F%' OR ProductName LIKE '%@F%' OR Price LIKE '%@F%' OR Comment LIKE '%@F%' ",
new SqlConnection(Program.ConnectionString)))
{
cmd.Parameters.AddWithValue("@F", find);
cmd.Connection.Open();
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
ProductTable.Rows.Add
(
(int)myReader["ID"],
myReader["BarCode"].ToString(),
myReader["ArtNumber"].ToString(),
myReader["ProductName"].ToString(),
(decimal)myReader["Price"],
(decimal)myReader["SelfPrice"],
(decimal)myReader["PriceWithOutAWD"],
myReader["TotalSelfPrice"].ToString(),
myReader["UnitsInStock"].ToString(),
myReader["Comment"].ToString(),
myReader["InputDateTime"].ToString(),
myReader["InputQuantity"].ToString(),
myReader["Margin"].ToString(),
myReader["CategoryName"].ToString(),
myReader["TypeName"].ToString(),
myReader["ExpDate"].ToString()
);
}
cmd.Connection.Close();
}
}
catch (Exception)
{
MessageBox.Show(Program.MsgError1, "Acid", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
... FROM GetProducts"+
"WHERE BarCode LIKE ...
应该是(请注意GetProducts
和WHERE
之间的额外空间)
... FROM GetProducts "+
"WHERE BarCode LIKE ...
也不要用
WHERE BarCode LIKE '%@F%'
可以使用
WHERE BarCode LIKE '%' + @F + '%'
或者让参数值包含通配符并使用
cmd.Parameters.AddWithValue("@F", "%" + find + "%");
...
WHERE BarCode LIKE @F
如果您始终使用前导通配符进行搜索,则应该使用
WHERE CHARINDEX(@F,BarCode) > 0
您的查询将始终无法使用索引,并且如果用户搜索的子字符串中包含在模式语法中具有特殊含义的字符,则此方法可避免出现问题。
但是,无论从搜索的列数还是前导通配符的角度来看,您都应该为此使用全文索引。
似乎您正在尝试在字符串文字内部引用参数:
WHERE BarCode LIKE '%@F%'
在这种情况下,我认为您被困在连接一些sql:
" WHERE BarCode LIKE '%" + find + "%' "
只需确保您从find中转义了所有撇号(并保护自己免受一般的SQL Injection ):
find = find.Replace("'","''");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.