[Tutor] Passing a list, dict or tuple to MySQLdb?
Alan Wardroper
python at wardroper.org
Thu Mar 8 00:55:53 CET 2007
I'm parsing some data to feed to a MySQL database, and would like to be
able to pass in a list (a dictionary or a series of tuples) in the
cursor.execute() or cursor.executemany() statement, but everything I've
tried raises errors. I'm sure it's a matter of correct formatting the
list as a sequence...
CODE:
import sys, MySQLdb
conn = MySQLdb.connect (host = "localhost", user = "user", psswd =
"xxxx" db = "testdb")
cursor = conn.cursor()
infile = open(sys.argv[2], 'r')
list_of_tuples = []
for line in infile:
tuple = (line.split()[0], line.split()[1])
list_of_tuples.append(tuple)
cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s WHERE
field2 = %s", (list_of_tuples)
"""
example data:
ID123445 somestring1
ID223445 somestring2
ID323445 somestring3
ID423445 somestring4
ID523445 somestring5
"""
Naively, I thought this would result in an execute statement like:
cursor.executemany("UPDATE LOW_PRIORITY sometable SET field1 = %s WHERE
field2 = %s", ('ID123445', 'somestring1'), ('ID223445', 'somestring2'),
('ID323445', 'somestring3'), ('ID423445', 'somestring4'), ('ID523445',
'somestring5'))
But what I get are bunch of errors, last of which is:
TypeError: not ll arguments converted during string formatting
Or pass in a list of values to use in a SELECT...WHERE...IN (list)
statement:
ids_to_include = ['ID123445', 'ID223445', 'ID323445']
cursor.execute("UPDATE sometable SET field1 = 'some standard value'
WHERE field2 IN (%s)", (ids_to_include))
I also tried another similar thing, where I tried to pass in the name of
one of the fields as a dictionary key with the value as the
corresponding value, but it also didn't work--it looked like the key was
bounded in quotes before passing to MySQL, so the db didn't recognise
the fieldname:
for key in dict.keys():
cursor.execute("INSERT INTO sometable (%s) values (%s)", (key,
dict[key]))
Any pointers?
Thanks
More information about the Tutor
mailing list