Insert a python dict into an SQLite DB

若如初见. 提交于 2021-02-07 08:12:54

问题


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.

Query="INSERT INTO packages VALUES("
    for tag in Tags:
       Query=Query + '"' + Package[tag] + '", '
    Query=Query[:-2]+")"
cursor.execute(Query)

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:

fields = Package.keys()
values = Package.values()
query = "INSERT INTO packages (%s) VALUES (%%s);" % (",".join(fields))
cursor.execute(query, values)

but it throws a type error.

TypeError: function takes at most 2 arguments (38 given)

The most elegant solution I have come across so far appears to be

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)

but it throws an operational error, saying

sqlite3.OperationalError: near "%": syntax error

Once again, my question is how can I elegantly safely add the values from a dictionary to a database?

P.S. It may also be worthy to note that I am using Python 2.5.1.


回答1:


Afaik, when query has a "?" placeholder execute() method does right escaping automatically basing on argument types. So, the following should work:

query = 'INSERT INTO packages VALUES(%s)' % ','.join(['?'] * len(Tags))
cursor.execute(query, Tags)



回答2:


I have come across the same problem however i had the problem that not all dictionary entries contained all columns of the table therefore i created the following solution

keys, values = zip(*Package.items())
insert_str =   "INSERT INTO packages (%s) values (%s)" % (",".join(keys),",".join(['?']*len(keys)))
cursor.execute(insert_str,values)


来源:https://stackoverflow.com/questions/8814250/insert-a-python-dict-into-an-sqlite-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!