Inserting NULL values using SQLAlchemy in PostgreSQL
Let us use the same insert() and values() function to insert NULL values. In python NULL equivalent is None. So, specify None for the records which you wish to insert as NULL values as shown below.
Python3
# specify null values as NONE statement6 = book_publisher.insert().values( publisherId = 6 , publisherName = None , publisherEstd = None ) # insert the null values engine.execute(statement6) |
Output:
You can see a new record inserted into row 6.
Fetching the above results using python shell
Here we are going to fetch the results using fetchall() methods.
Python3
# Get the `book_publisher` table from the # Metadata object import sqlalchemy book_publisher = meta.tables[ 'book_publisher' ] # SQLAlchemy Query to fetch all records query = sqlalchemy.select([ book_publisher]) # Fetch all the records result = engine.execute(query).fetchall() # View the records for record in result: print ( "\n" , record) |
Output:
How to insert NULL value in SQLAlchemy?
In this article, we will see how to insert NULL values into a PostgreSQL database using SQLAlchemy in Python.
For demonstration purposes first, let us create a sample table using SQLAlchemy as shown below