Add json field to postgres with python

Python -- Posted on March 11, 2021

The provided Python code connects to a PostgreSQL database, creates a table with a JSON column, inserts a JSON object into the table, and then closes the connection to the database.

 

              
                import psycopg2
from psycopg2 import Error
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import json
try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="mydatabase")
    connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

    # Create a cursor to perform database operations
    commands = (
        """drop table examplejson """,
        """create table examplejson(
            id serial primary key not null,
            data JSON
            );""",
    )
    cursor = connection.cursor()

    for command in commands:
        cursor.execute(command)
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")
    pitem = {
        "name": 'pc',
        "category": 'desktop pc'
    }
    cursor.execute("INSERT INTO examplejson(data) VALUES (%s)", (json.dumps(pitem),))
    connection.commit()

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)

finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
                  
   
            

Related Posts