【问题标题】:I've been tried to insert a record to sql table using tkinter with entry widget, but i got an sql syntax error我曾尝试使用带有条目小部件的 tkinter 将记录插入到 sql 表中,但出现 sql 语法错误
【发布时间】:2021-01-09 05:39:03
【问题描述】:

这是我的更新:

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)

这是我得到的错误: pymysql.err.ProgrammingError: (1064, "您的 SQL 语法有错误;请查看与您的 MariaDB 服务器版本相对应的手册,了解在 ''Vanes'、'1 June 2003'、'Grand Hill 附近使用的正确语法23', '091293812030')' 在第 1 行")

【问题讨论】:

  • 最好使用占位符:sql = "INSERT INTO petugas VALUES (%s, %s, %s, %s)",然后是cur.execute(sql, insert)
  • 感谢您回答我的问题,但我遇到了同样的错误,希望您能看到我的更新
  • 你应该在""包围的字符串中使用''

标签: python sql tkinter pymysql tkinter-entry


【解决方案1】:

通过 python 对 sql 查询使用连接是不安全的,因为它容易受到 sql 注入的影响。我建议尝试使用占位符(%s) 和参数替换,例如:

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()

希望这可以清除您的错误,如果有任何疑问,请告诉我。

干杯

【讨论】:

  • 感谢您回答我的问题,但我仍然遇到同样的错误。你有什么建议吗?
  • 感谢您的帮助,现在我的程序运行成功了。
  • NULL 不应被 " 包围。
  • @acw1668 没错,我更新了正确的。 This totally误导了我
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 2019-07-14
  • 1970-01-01
  • 2019-08-09
  • 2020-04-16
  • 2014-08-10
  • 1970-01-01
  • 2011-02-26
相关资源
最近更新 更多