'MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax;

Please help, im trying to build a classroom scheduling system, so the system is almost complete, i can debug the system but whenever i go to set some schedules, it shows this kind of message

MySql.Data.MySqlClient.MySqlException:

'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''SELECT subj.sub_code, subj.sub_desc, start_time, end_time, days, item_color, pr' at line 1'

What should I do? Please help. heres the part of the code that im guessing that it has a problem

Dim constring As String = "server=localhost;user id='root';password='!Password123';database = 'scheduling'"
Using con As New MySqlConnection(constring)
    sql = "'SELECT subj.sub_code, subj.sub_desc, start_time, end_time, days, item_color, pr_id, sched.sched_id, sched.course_id FROM tblschedule AS sched INNER JOIN open_subjects AS op_sub ON sched.sub_code = op_sub.sub_code INNER JOIN subject AS subj ON op_sub.sub_code = subj.sub_code WHERE sched.room_id ='" & room_id & "' AND op_sub.semester = '" & school_semester_text & "' AND op_sub.sy = '" & school_year_text & "' AND sched.void = 0 '"
    cmd = New MySqlCommand(sql, con)
    cmd.CommandType = CommandType.Text
    Using sda As New MySqlDataAdapter(cmd)
        Using ds As New DataSet()
            sda.Fill(ds, "tblschedule")
            Using dt As DataTable = ds.Tables("tblschedule")


Solution 1:[1]

Dim constring As String = "server=localhost;user id=root;password=########;database=scheduling"
Dim sql As String = "
SELECT subj.sub_code, subj.sub_desc, start_time, end_time, days, item_color, pr_id, sched.sched_id, sched.course_id 
FROM tblschedule AS sched 
INNER JOIN open_subjects AS op_sub ON sched.sub_code = op_sub.sub_code
INNER JOIN subject AS subj ON op_sub.sub_code = subj.sub_code 
WHERE sched.room_id = @room_id AND op_sub.semester = @semester AND op_sub.sy = @year AND sched.void = 0
"

Dim dt As New DataTabe()
Using con As New MySqlConnection(constring), _
      cmd As New MySqlCommand(sql, con), _
      sda As New MySqlDataAdapter(cmd)

    cmd.Parameters.AddWithValue("@room_id", room_id)
    cmd.Parameters.AddWithValue("@semester", school_semester_text)
    cmd.Parameters.AddWithValue("@year", school_year_text)
    sda.Fill(dt)
End Using

Note how I used the parameters instead of string concatenation. This is how you must do it if you don't want your application to end up horribly hacked.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1