-2

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(); and 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.

Yuck
  • 49,664
  • 13
  • 105
  • 135
Lahno
  • 21
  • 1
  • 1
  • 3

3 Answers3

2

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).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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);
Yuck
  • 49,664
  • 13
  • 105
  • 135
  • 1
    Thank you both. I'm studying computer science and only for 6 month, so still learning. And it works now. GREAT! :) – Lahno Sep 12 '11 at 12:44
1

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 + "'";