简体   繁体   English

将python GUI链接到MySQL数据库

[英]Linking python GUI to MySQL database

I'm a nube at the Python language and I'm having a hard time linking my Python GUI (in Tkinter) to a database. 我是Python语言的nube,我很难将我的Python GUI(在Tkinter中)链接到数据库。 The layout is such that I want the end user to add Names to a database through an Entry widget. 布局是这样的,我希望最终用户通过Entry小部件将Names添加到数据库。 I tried to get the text to save to the database by using a variable, something like: 我尝试使用变量将文本保存到数据库,例如:

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

this gives back the error message: 这会返回错误消息:

TypeError: query() argument 1 must be string or read-only buffer, not tuple

is there any way I can save data from the entry widget to the database without having to use var1 = raw_input("Name: ") somewhere else instead? 有没有什么办法可以将数据从条目小部件保存到数据库,而不必在其他地方使用var1 = raw_input("Name: ")

Thank you for your time! 感谢您的时间! :) :)

Replace 更换

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

with (preferred) 与(首选)

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

or 要么

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

If you wonder why your code did not work: Passing a tuple as a function argument will pass it as a single argument; 如果你想知道为什么你的代码不起作用:将元组作为函数参数传递将它作为单个参数传递; while , creates tuples, it only does so if it's not inside a function declaration/call - in there it's the argument separator. 虽然,创建元组,它只会这样做,如果它不在函数声明/调用 - 在那里它是参数分隔符。

Using *sql_update unpacks the tuple into positional arguments so it works again. 使用*sql_update将元组解压缩为位置参数,以便它再次起作用。 However, since you probably just use the variable to keep your code lines shorter, only put the SQL string in there and create the tuple inline when calling cur.execute() . 但是,由于您可能只是使用该变量来缩短代码行,因此只需将SQL字符串放在那里并在调用cur.execute()时创建元组内联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM