I want to enter in the database values ​​from the keyboard

Flight flight = new Flight(); SqlCommand addflight = new SqlCommand(); addflight.Connection =Sqlcon; Console.WriteLine("Enter Arrival Date"); flight.Arrival = EnterData(); Console.WriteLine("Enter Departure Date"); flight.Departure = EnterData(); Console.Write("Enter Flight number="); flight.Flight_Number = Convert.ToString(Console.ReadLine()); Console.Write("Enter City of arrival="); flight.City_of_arrival = Convert.ToString(Console.ReadLine()); Console.Write("Enter City of departure="); flight.City_of_Departure = Convert.ToString(Console.ReadLine()); Console.Write("Enter Terminal="); flight.Terminal = Convert.ToString(Console.ReadLine()); Console.Write("Enter Flight status="); flight.Flight_Status = Convert.ToString(Console.ReadLine()); Console.Write("Enter Gate="); flight.Gate= Convert.ToString(Console.ReadLine()); // addflight.CommandText = "INSERT INTO Flights(Arrival,Departure,Flight_Number,City_of_arrival,City_of_departure,Terminal,Flight_Status,Gate,ID) VALUES (2007-05-08 12:35:29.123,2007-05-08 12:35:29.123,s,s,s,s,s,s,s,1)"; addflight.CommandText = "INSERT INTO Flights(Arrival,Departure,Flight_Number,City_of_arrival,City_of_departure,Terminal,Flight_Status,Gate,ID) VALUES("+ "20120618 10:34:09 AM" + ","+ "20120618 10:34:09 AM" + ","+flight.Flight_Number+","+flight.City_of_arrival+","+flight.City_of_Departure +","+flight.Terminal+","+flight.Flight_Status+","+flight.Gate+","+ID+")"; ID++; try { addflight.ExecuteNonQuery(); } catch(Exception ex) { Console.WriteLine(ex.Message); } } 

When using the INSERT INTO command, a message about Exception is displayed on the screen. Inccorrect Syntax near 10. What's wrong with the CommandText? Maybe there is a better way to do this?

    1 answer 1

    Do not collect CommandText through +, use the parameters:

     addflight.CommandText = "INSERT INTO Flights(Arrival,Departure,...,ID) VALUES(@Arrival, @Departure .... )"; addflight.Parameters.AddWithValue("@Arrival", flight.Arrival); addflight.Parameters.AddWithValue("@Departure", flight.Departure); //.... 

    And you will not have errors with the parsing of dates and other SQL injections.