I have some trouble with the SqlDataReader
:
public string GetVareNavn(string streg)
{
string navn = "";
SqlConnection myCon = DBcon.getInstance().conn();
string query =
"SELECT Navn FROM Vare WHERE Stregkode = ) Values('" + streg + "')";
myCon.Open();
SqlCommand com = new SqlCommand(query, myCon);
Console.WriteLine("navn: "+navn);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
navn = dr.GetString(1);
}
myCon.Close();
return navn;
}
It throws an exception at com.ExecutiveReader();
开发者_如何学Pythonand the exception is:
Incorrect syntax near ')'.
I don't know why this one doesn't work right now, because I've used it in another project.
Your query looks like it was copied from something that used to be an INSERT
statement; you don't need the VALUES...
clause at the end of the statement. Try changing your query
to:
string query =
"SELECT Navn FROM Vare WHERE Stregkode = @streg";
Then modify this code to use the parameter:
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.AddWithValue("@streg", streg);
It doesn't work because your SQL is broken:
SELECT Navn FROM Vare WHERE Stregkode = ) Values('" + streg + "')"
What did you expect that WHERE
clause to do, and what values are you trying to use? It looks like you've got a broken copy/paste from an update command.
Additionally, you shouldn't put values into your SQL like that anyway - you should use parameterized queries to avoid SQL injection attacks (and to avoid formatting issues etc).
Ya, surely it will give. Why you put the Values
in your select
query? which is wrong syntax, Try Now.
string query = "SELECT Navn FROM Vare WHERE Stregkode = '" + streg + "'";
精彩评论