I'm getting a sqlexception while im trying to select some values. The error: Incorrect syntax near '@navn'. I've looked around to find other questions similar to mine, but I can't find anything worth to me.
My code:
public List<Vare> findvareAdvanced(string varenavn)
{
Vare v = new Vare();
List<Vare> lv = new List<Vare>();
SqlConnection myCon = DBcon.getInstance().conn();
string query = string.Format开发者_StackOverflow中文版("SELECT * FROM Vare WHERE Navn LIKE %@navn%");
myCon.Open();
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.AddWithValue("navn", varenavn);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
v.Stregkode = dr.GetString(0);
v.Navn = dr.GetString(1);
v.Pris = dr.GetDecimal(2);
v.Varegruppenr = dr.GetInt32(3);
lv.Add(v);
}
myCon.Close();
return lv;
}
Try,
string query = string.Format("SELECT * FROM Vare WHERE Navn LIKE @navn");
com.Parameters.AddWithValue("@navn", "%" + varenavn + "%");
forgot the ' ?
string query = string.Format("SELECT * FROM Vare WHERE Navn LIKE '%@navn%' ");
If you want a literal translation of the string, add an @
symbol before the string. This will help handle escape characters
This question might also help
string query = string.Format(@"SELECT * FROM Vare WHERE Navn LIKE %@navn%");
精彩评论