SQL Server And C# WinForms error
I call this method on form load ivent GetProducts(" "); This Query works fine in sql. It was working till i added WHERE When i use debugger on this line >> SqlDataReader myReader = cmd.ExecuteReader(); Can anyone advice me something?
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"+
开发者_StackOverflow中文版 "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 ...
Should be (note additional space between GetProducts
and WHERE
)
... FROM GetProducts "+
"WHERE BarCode LIKE ...
Also don't use
WHERE BarCode LIKE '%@F%'
Either Use
WHERE BarCode LIKE '%' + @F + '%'
Or alternatively have the parameter value contain the wild cards and use
cmd.Parameters.AddWithValue("@F", "%" + find + "%");
...
WHERE BarCode LIKE @F
If you will always be searching with a leading wildcard however you should probably use
WHERE CHARINDEX(@F,BarCode) > 0
Your query won't be able to use an index anyway and this method avoids issues if the users search for substrings that contain characters that have a special meaning in the pattern syntax.
However from the amount of columns you are searching and the leading wildcards you should probably use full text indexing for this anyway.
It looks like you're trying to reference a parameter inside of a string literal:
WHERE BarCode LIKE '%@F%'
In this case, I think you're stuck concatenating some sql:
" WHERE BarCode LIKE '%" + find + "%' "
Just make sure you escape any apostrophes from find (and protect yourself from SQL Injection in general):
find = find.Replace("'","''");
精彩评论