将python GUI链接到MySQL数据库

时间:2012-03-27 23:00:06

标签: python mysql-python

我是Python语言的nube,我很难将我的Python GUI(在Tkinter中)链接到数据库。布局是这样的,我希望最终用户通过Entry小部件将Names添加到数据库。我尝试使用变量将文本保存到数据库中,例如:

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

这会返回错误消息:

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

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

感谢您的时间! :)

1 个答案:

答案 0 :(得分:4)

替换

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

与(首选)

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

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

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

使用*sql_update将元组解压缩为位置参数,以便它再次起作用。但是,由于您可能只是使用该变量来缩短代码行,因此只需将SQL字符串放在那里并在调用cur.execute()时创建元组内联。