Python Sqlite3: INSERT INTO table VALUE(dictionary goes here)

2024/11/19 11:24:24

I would like to use a dictionary to insert values into a table, how would I do this?

import sqlite3db = sqlite3.connect('local.db')
cur = db.cursor()cur.execute('DROP TABLE IF EXISTS Media')cur.execute('''CREATE TABLE IF NOT EXISTS Media(id INTEGER PRIMARY KEY, title TEXT, type TEXT,  genre TEXT,onchapter INTEGER,  chapters INTEGER,status TEXT)''')values = {'title':'jack', 'type':None, 'genre':'Action', 'onchapter':None,'chapters':6,'status':'Ongoing'}#What would I Replace x with to allow a 
#dictionary to connect to the values? 
cur.execute('INSERT INTO Media VALUES (NULL, x)'), values)
cur.execute('SELECT * FROM Media')meida = cur.fetchone()print meida
Answer

If you're trying to use a dict to specify both the column names and the values, you can't do that, at least not directly.

That's really inherent in SQL. If you don't specify the list of column names, you have to specify them in CREATE TABLE order—which you can't do with a dict, because a dict has no order. If you really wanted to, of course, you could use a collections.OrderedDict, make sure it's in the right order, and then just pass values.values(). But at that point, why not just have a list (or tuple) in the first place? If you're absolutely sure you've got all the values, in the right order, and you want to refer to them by order rather than by name, what you have is a list, not a dict.

And there's no way to bind column names (or table names, etc.) in SQL, just values.

You can, of course, generate the SQL statement dynamically. For example:

columns = ', '.join(values.keys())
placeholders = ', '.join('?' * len(values))
sql = 'INSERT INTO Media ({}) VALUES ({})'.format(columns, placeholders)
values = [int(x) if isinstance(x, bool) else x for x in values.values()]
cur.execute(sql, values)

However, this is almost always a bad idea. This really isn't much better than generating and execing dynamic Python code. And you've just lost all of the benefits of using placeholders in the first place—primarily protection from SQL injection attacks, but also less important things like faster compilation, better caching, etc. within the DB engine.

It's probably better to step back and look at this problem from a higher level. For example, maybe you didn't really want a static list of properties, but rather a name-value MediaProperties table? Or, alternatively, maybe you want some kind of document-based storage (whether that's a high-powered nosql system, or just a bunch of JSON or YAML objects stored in a shelve)?


An alternative using named placeholders:

columns = ', '.join(my_dict.keys())
placeholders = ':'+', :'.join(my_dict.keys())
query = 'INSERT INTO my_table (%s) VALUES (%s)' % (columns, placeholders)
print query
cur.execute(query, my_dict)
con.commit()
https://en.xdnf.cn/q/26449.html

Related Q&A

Count the uppercase letters in a string with Python

I am trying to figure out how I can count the uppercase letters in a string. I have only been able to count lowercase letters:def n_lower_chars(string):return sum(map(str.islower, string))Example of w…

Multithreading for Python Django

Some functions should run asynchronously on the web server. Sending emails or data post-processing are typical use cases.What is the best (or most pythonic) way write a decorator function to run a func…

run a crontab job using an anaconda env

I want to have a cron job execute a python script using an already existing anaconda python environment called my_env. The only thing I can think to do is have the cron job run a script called my_scri…

pandas - Merging on string columns not working (bug?)

Im trying to do a simple merge between two dataframes. These come from two different SQL tables, where the joining keys are strings:>>> df1.col1.dtype dtype(O) >>> df2.col2.dtype dtyp…

Making a chart bigger in size

Im trying to get a bigger chart. However, the figure method from matplotlib does not seem to be working properly. I get a message, which is not an error: <matplotlib.figure.Figure at 0xa25f7f0>My…

index of non NaN values in Pandas

From Pandas data frame, how to get index of non "NaN" values?My data frame isA b c 0 1 q1 1 1 2 NaN 3 2 3 q2 3 3 4 q1 NaN 4 5 q2 7And I want the…

How can I type-check variables in Python? [duplicate]

This question already has answers here:Whats the canonical way to check for type in Python?(16 answers)Closed 3 months ago.I have a Python function that takes a numeric argument that must be an intege…

Py_INCREF/DECREF: When

Is one correct in stating the following:If a Python object is created in a C function, but the function doesnt return it, no INCREF is needed, but a DECREF is. [false]If the function does return it, yo…

pop/remove items out of a python tuple

I am not sure if I can make myself clear but will try.I have a tuple in python which I go through as follows (see code below). While going through it, I maintain a counter (lets call it n) and pop item…

Difference between frompyfunc and vectorize in numpy

What is the difference between vectorize and frompyfunc in numpy?Both seem very similar. What is a typical use case for each of them?Edit: As JoshAdel indicates, the class vectorize seems to be built…