简体   繁体   中英

System.Data.SqlClient.SqlException: Incorrect syntax near ')'

I am getting an error in my SQL command with which I am trying to retrieve values from a SQL Server database. It is showing a error in browser as mentioned in title. If I remove the brackets it shows error in AND operator

string jdate = (string)Session["jdate"];
string clas = (string)Session["class"];
string scode = (string)Session["scode"];
string dcode = (string)Session["dcode"];
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ToString());

// error shows up on this line 
string slct = "SELECT Route.Route_Source, Route.Route_Destination, Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time, Schedule.Route_rate_Ad , Seats." + jdate + 
              "Schedule.Sch_id FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id INNER JOIN Route ON Schedule.Route_id = Route.Route_id INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id WHERE (Route.Route_Source =" + scode + ") AND (Route.Route_Destination =" + dcode + ") AND (Seats.Class=" + clas + ") ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";

cn.Open();

SqlDataAdapter da = new SqlDataAdapter(slct, cn);
DataSet ds = new DataSet();
da.Fill(ds);

SearchView.DataSource = ds;
SearchView.DataBind();

You should use a parameterized query.
This would allow a more understandable query text, avoid simple syntax errors
(like the missing comma at the end of the first line (jdate)),
avoid Sql Injections and parsing problems with strings containing quotes or decimal separators

string slct = @"SELECT Route.Route_Source, Route.Route_Destination, 
               Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time, 
               Schedule.Route_rate_Ad, Seats." + jdate + ", Schedule.Sch_id " +
               @"FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id 
                         INNER JOIN Route ON Schedule.Route_id = Route.Route_id 
                         INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id 
                 WHERE (Route.Route_Source = @scode) 
                    AND (Route.Route_Destination =@dcode) 
                    AND (Seats.Class=@class) 
                 ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";

cn.Open();
SqlCommand cmd = new SqlCommand(slct, cn);
cmd.Parameters.AddWithValue("@scode", scode);
cmd.Parameters.AddWithValue("@dcode", dcode);
cmd.Parameters.AddWithValue("@class", clas);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM