Note that there are some explanatory texts on larger screens.

plurals
  1. POInsert a python dict into an SQLite DB
    primarykey
    data
    text
    <p>I have a dictionary that I want to add all the values to an sqlite database. All the keys in the dictionary exist in the database, and all the keys are of type string. Yet, I am having trouble with getting the values into the database. The following code is ugly, insecure, and errors whenever it comes across a string with a " in it, but it sort of works. </p> <pre><code>Query="INSERT INTO packages VALUES(" for tag in Tags: Query=Query + '"' + Package[tag] + '", ' Query=Query[:-2]+")" cursor.execute(Query) </code></pre> <p>How can I elegantly fix this so that it is secure and accepts inputs with " in the string? I've come across a handful of other methods. For example:</p> <pre><code>fields = Package.keys() values = Package.values() query = "INSERT INTO packages (%s) VALUES (%%s);" % (",".join(fields)) cursor.execute(query, values) </code></pre> <p>but it throws a type error. </p> <pre><code>TypeError: function takes at most 2 arguments (38 given) </code></pre> <p>The most elegant solution I have come across so far appears to be</p> <pre><code>sql_insert = ('INSERT INTO packages (%s) VALUES (%s)' % (','.join('%s' % name for name in Package), ','.join('%%(%s)s' % name for name in Package))) cursor.execute(sql_insert, Package) </code></pre> <p>but it throws an operational error, saying</p> <pre><code>sqlite3.OperationalError: near "%": syntax error </code></pre> <p>Once again, my question is how can I elegantly safely add the values from a dictionary to a database? </p> <p>P.S. It may also be worthy to note that I am using Python 2.5.1. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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