Is there a good practice for entering NULL key values to a PostgreSQL database when a variable is None in Python?
Running this query:
mycursor.execute('INSERT INTO products (user_id, city_id, product_id, quantity, price) VALUES (%i, %i, %i, %i, %f)' %(user_id, city_id, product_id, quantity, price))
results in a a TypeError exception when user_id is None.
How can a NULL be inserted into the database when a value is None, using the psycopg2 driver?
To insert
nullvalues to the database you have two options:NoneAlso: To guard against SQL-injection you should not use normal string interpolation for your queries.
You should pass two (2) arguments to
execute(), e.g.:Alternative #2: