将python GUI链接到MySQL数据库

2024-05-23 20:03:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python语言的nube,很难将pythongui(用Tkinter)链接到数据库。布局是这样的,我希望最终用户通过条目小部件向数据库添加名称。我试图使用一个变量将文本保存到数据库中,例如:

entr= Entry(frame1)
entr.grid(row=0, column=1)

var1=entr.get()

def save():
    """Save content in the entry box"""
    con = mdb.connect(host="localhost", user="root", passwd="xxxxxx", db="xxxxxxx")
    with con:
        cur=con.cursor()
        sql_update= "UPDATE Tests SET NAME='%s' WHERE id='%s'", (var1, id)
        cur.execute(sql_update)
        cur.close()
        con.commit()
        con.close()

这将返回错误消息:

^{pr2}$

有什么方法可以不必在其他地方使用var1 = raw_input("Name: ")将数据从条目小部件保存到数据库吗?在

感谢您抽出时间!:)


Tags: 语言id数据库closesql部件tkinterupdate
1条回答
网友
1楼 · 发布于 2024-05-23 20:03:49

更换

    sql_update= "UPDATE Tests SET NAME='%s' WHERE id='%s'", (var1, id)
    cur.execute(sql_update)

带(首选)

^{pr2}$

或者

    sql_update= "UPDATE Tests SET NAME=%s WHERE id=%s", (var1, id)
    cur.execute(*sql_update)

如果您想知道代码为什么不起作用:将元组作为函数参数传递将作为单个参数传递;当,创建元组时,它只在它不在函数声明/调用内部时才这样做-在那里它是参数分隔符。在

使用*sql_update将元组解压为位置参数,这样它就可以再次工作了。但是,由于您可能只是使用变量来缩短代码行,所以只需在调用cur.execute()时将SQL字符串放入其中并创建元组内联。在

相关问题 更多 >