简体   繁体   中英

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. The layout is such that I want the end user to add Names to a database through an Entry widget. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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