Search code examples
mysqlsyntax-errorparameterized-queryinsert-statement

Syntax Error in InsertStatement


Im inserting a data in MySql database and when I click the save button, it says,

You have an error in sql syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "grade1") VALUES('section1')' at line 1"

I copied it from other insert statement that works fine, but in the form that contains combobox and a textbox only, it gives me that kind of error. They also want me to learn how to paramerized it so Im free from SQL injection they say. Any help is appreciated. Here's the sample codes:

conn = New MySqlConnection
conn.ConnectionString = "server=localhost; userid=root; password=root; database=dbase"

Try

    conn.Open()
    Sql = "INSERT INTO dbase.tblgrade_section ('" & cbGradeLvl.SelectedItem & "') VALUES('" & txtNewSec.Text & "') "
    cmd = New MySqlCommand(Sql, conn)
    dr = cmd.ExecuteReader
    MsgBox("Data saved", vbInformation, "Saving Data")
    conn.Close()

Catch ex As Exception
    MsgBox(ex.Message)
Finally
    conn.Close()
End Try
rem End Sub

Solution

  • Basic MySQL 101: Fields/Table names cannot be quoted with anything other than backticks. You've used ', which turns your field name into a string literal. ONce it's a string literal, it's no longer a table/field name:

    Sql = "INSERT INTO dbase.tblgrade_section (`" & cbGradeLvl.Selected ... "`...."
                                               ^-----------------------------^---
    

    note the indicated changes.