Tim Berry
Tim Berry

Reputation: 57

python mysql UPDATE doesn't work without WHERE clause

    def WriteToDB():
import mysql.connector
var1 = comboboxRow1x1.get(), comboboxRow1x2.get()
var2="happy"
cnx = mysql.connector.connect(user='me', password='mine',
                            host='localhost',
                            database='testdb')
cursor = cnx.cursor()

cursor.execute ("""
        UPDATE curweek
        SET row1=%s
        WHERE row3=%s;
        """, (str(var1), var2))
cnx.commit()
cnx.close()

The Above works, but when I remove the WHERE, it errors;

line 91, in WriteToDB """, (str(var1))) File "/usr/lib/python2.7/site-packages/mysql/connector/cursor.py", line 381, in execute "Wrong number of arguments during string formatting") ProgrammingError: Wrong number of arguments during string formatting

This is one of the ways I tried removing the WHERE;

    def WriteToDB():
import mysql.connector
var1 = comboboxRow1x1.get(), comboboxRow1x2.get(), comboboxRow1x3.get()
#var2="happy"
cnx = mysql.connector.connect(user='me', password='mine',
                            host='localhost',
                            database='testdb')
cursor = cnx.cursor()

cursor.execute ("""
        UPDATE curweek
        SET row1=%s;
        """, (str(var1)))
cnx.commit()
cnx.close()

Thanks much for help. Formatting is off here - I haven't posted enough to get it perfect yet but in my file its as it should be I think.

Upvotes: 1

Views: 312

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

You need to pass a tuple (note the extra comma):

cursor.execute("UPDATE curweek SET row1=%s;", (str(var1),))

If you omit the comma, you are passing a string:

>>> i = 'hello'
>>> z = (i)
>> z
'hello'
>>> type(z)
<type 'str'>
>>> z = (i,)
>>> type(z)
<type 'tuple'>
>>> z
('hello',)

Upvotes: 2

Related Questions