0

I am trying to read an integer from a SQL Server database by text in comboboxes. I get a "Syntax error" "near" my Table name "Seeweg". The debugger does not highlight the line, where the error happens.

The column with the value I like to get is named seadistance. The other columns, by which to sort are start and ziel.

They get sorted by the values written in the comboboxes.

To reproduce this procedure I inserted the code into a class and called the instance by a button named btnSea.

I already searched for similar problems, but I could not find any syntax errors concerning the string implementation. The column names are correct.

//The Button
private void btnSea_Click(object sender, EventArgs e)
        {
            Entnehmen CO2 = new Entnehmen();
            int Dist = CO2.Werte("Seeweg", "start", "ziel", "seadistance", comboSeaOrig.Text, comboSeaDest.Text);
            MessageBox.Show(Dist.ToString());
        }
//The class
class Entnehmen
{
        public int Werte(string Tabelle, string Reihe1, string Reihe2, string Wertereihe, string WertReihe1, string WertReihe2)
        {
            int Wert = 0;
            string myConnection = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";

            using (SqlConnection myConn = new SqlConnection(myConnection))
            {
                myConn.Open();
                SqlCommand SelectCommand = new SqlCommand("SELECT '" + Wertereihe + "' FROM '" + Tabelle + "' WHERE '" + Reihe1 + "' = '" + WertReihe1 + "' AND '" + Reihe2 + "' = '" + WertReihe2 + "' ; ", myConn);
                Wert = (int)SelectCommand.ExecuteScalar();
            }
            return Wert;
        }
    }
}

I expect the value to be given back. Before that happens, I get the error:

Incorrect syntex near 'Seeweg'

Where is the syntax mistake? Any help is appreciated =)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bjay Earn
  • 13
  • 1
  • 2
    What is the **exact** value of `SqlCommand SelectCommand.CommandText`? – mjwills Jun 26 '19 at 13:24
  • Also please read https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection . – mjwills Jun 26 '19 at 13:25
  • Error indicates you have issue generating SqlCommand string. You can check what is generating there by printing the Script line you are creating. – mkRabbani Jun 26 '19 at 13:31

1 Answers1

2

You are generating something like:

SELECT 'seadistance' FROM 'Seeweg' WHERE 'start' = 'aa' AND 'ziel' = 'bbb'

This is not a valid T-SQL statement. Correct your quotes in columns and tables variables.

This is a suggestion of how you can write your T-SQL statemant based on your code:

SqlCommand SelectCommand = new SqlCommand("SELECT " + Wertereihe + " FROM " + Tabelle + " WHERE " + Reihe1 + " = '" + WertReihe1 + "' AND " + Reihe2 + " = '" + WertReihe2 + "' ; ", myConn);