The psycopg module

  1. Install the psycopg module

    $ python3 -m pip install psycopg
    Collecting psycopg
      Downloading psycopg-3.0.1-py3-none-any.whl (140 kB)
         |████████████████████████████████| 140 kB 3.4 MB/s
    Installing collected packages: psycopg
    Successfully installed psycopg-3.0.1
    
  2. Import the psycopg module

    1import psycopg2
    
  3. Create a database

    3conn = psycopg2.connect(dbname="my_db", user="username")
    4cursor = conn.cursor()
    
  4. Query the database

    7cursor.execute("SELECT * FROM my_table")
    8row = cursor.fetchone()
    
  5. Close cursor and connection

    11cursor.close()
    12conn.close()