Search code examples
pythonsqltkinterpymysqltkinter-entry

I've been tried to insert a record to sql table using tkinter with entry widget, but i got an sql syntax error


This is my update:

def submit():
    nama = Nama.get()
    tgl_lahir =  tgl_Lahir.get()
    alamat = Alamat.get()
    no_telp = No_telp.get()
    insert = (nama,tgl_lahir,alamat,no_telp)
    #connect to database
    db = pymysql.connect(db="db_petugas", host="localhost", passwd="", user="root")
    #prepare cursor
    cur = db.cursor()
    #insert into petugas table
    sql = "INSERT INTO petugas VALUES ("",%s, %s, %s, %s);"
    #execute sql code
    cur.execute(sql, insert)
    db.commit()
    db.close()
    #delete the entry
    Nama.delete(0, END)
    tgl_Lahir.delete(0, END)
    Alamat.delete(0, END)
    No_telp.delete(0, END)

This is error what i got: pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''Vanes', '1 June 2003', 'Grand Hill 23', '091293812030')' at line 1")


Solution

  • It is not safe to use concatenation with sql queries through python as it is vulnerable to sql injection. I recommend trying out to use placeholder(%s) and parametric substitution, like:

    sql = "INSERT INTO petugas VALUES (NULL, %s, %s, %s);" #Using placeholders
    # execute sql code
    cur.execute(sql,insert) #substituting the tuple as a parameter
    db.commit()
    db.close()
    

    Hope this cleared your error, do let me know if any doubts.

    Cheers