Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert 'NULL' values into PostgreSQL database using Python?

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?

like image 381
xpanta Avatar asked Nov 20 '10 06:11

xpanta


People also ask

How do I write NULL in PostgreSQL?

Example - With INSERT Statement INSERT INTO contacts (first_name, last_name) SELECT first_name, last_name FROM employees WHERE employee_number IS NULL; This PostgreSQL IS NULL example will insert records into the contacts table where the employee_number contains a NULL value.

How do you add a value to a NULL in Python?

Unlike other programming languages such as PHP or Java or C, Python does not have a null value. Instead, there is the 'None' keyword that you can use to define a null value.

How can I insert NULL data into mysql database with Python?

NULL is a special character when inserting into sql (without quotes). If you use the second insert, it would insert the string "NULL", bu the first will have a statement like: INSERT INTO table (var) VALUES (NULL) which will put a special NULL in for the value.


1 Answers

To insert null values to the database you have two options:

  1. omit that field from your INSERT statement, or
  2. use None

Also: 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.:

mycursor.execute("""INSERT INTO products                      (city_id, product_id, quantity, price)                      VALUES (%s, %s, %s, %s)""",                   (city_id, product_id, quantity, price)) 

Alternative #2:

user_id = None mycursor.execute("""INSERT INTO products                      (user_id, city_id, product_id, quantity, price)                      VALUES (%s, %s, %s, %s, %s)""",                   (user_id, city_id, product_id, quantity, price)) 
like image 68
mechanical_meat Avatar answered Sep 28 '22 01:09

mechanical_meat