[Tutor] Passing a list, dict or tuple to MySQLdb?

Bill Campbell bill at celestial.net
Thu Mar 8 01:05:27 CET 2007

On Wed, Mar 07, 2007, Alan Wardroper wrote:
>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...
>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)

I think what you want is ...(*list_of_tuples) similar to the syntax used
when calling functions with position arguments from a list.

INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

Few skills are so well rewarded as the ability to convince parasites that
they are victims. -- Thomas Sowell

More information about the Tutor mailing list