Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Before you post, you might want to try searching for something more specific to your question. For instance, when I Googled "python mysqldb insert dictionary", I found a good answer on the first page, at <a href="http://mail.python.org/pipermail/tutor/2010-December/080701.html" rel="nofollow">http://mail.python.org/pipermail/tutor/2010-December/080701.html</a>. Relevant part:</p> <blockquote> <p>Here's what I came up with when I tried to make a generalized version of the above:</p> <pre><code>def add_row(cursor, tablename, rowdict): # XXX tablename not sanitized # XXX test for allowed keys is case-sensitive # filter out keys that are not column names cursor.execute("describe %s" % tablename) allowed_keys = set(row[0] for row in cursor.fetchall()) keys = allowed_keys.intersection(rowdict) if len(rowdict) &gt; len(keys): unknown_keys = set(rowdict) - allowed_keys print &gt;&gt; sys.stderr, "skipping keys:", ", ".join(unknown_keys) columns = ", ".join(keys) values_template = ", ".join(["%s"] * len(keys)) sql = "insert into %s (%s) values (%s)" % ( tablename, columns, values_template) values = tuple(rowdict[key] for key in keys) cursor.execute(sql, values) filename = ... tablename = ... db = MySQLdb.connect(...) cursor = db.cursor() with open(filename) as instream: row = json.load(instream) add_row(cursor, tablename, row) </code></pre> <p>Peter</p> </blockquote> <p>If you know your inputs will always be valid (table name is valid, columns are present in the table), and you're not importing from a JSON file as the example is, you can simplify this function. But it'll accomplish what you want to accomplish. While it may initially seem like DictCursor would be helpful, it looks like DictCursor is useful for <em>returning</em> a dictionary of values, but it can't execute from a dict.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload