Define a new PostgreSQL connection in Python

Define new PostgreSQL database connection and store credentials in .env file. To dofine a new connection provide your:

  • database name
  • username
  • password
  • host adress
  • port
This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

All required packages are automatically imported by MLJAR Studio for you so you don't have to worry about them.

# import packages
import os

When you use Define a new connection recipe it adds your credentials to a .env file. You need to do this only once. When you connect to database next time, it will use those saved credentails.

The code bellow is there to inform you that everything was executed correctly.

print("Database connection credentials stored in .env file successfully.")

Conclusions

Defining a new connection is simple and easy process, and you only need to do it once! Check out our other notebooks to learn how to connect to your database and query it for data.

Recipes used in the postgresql-python-define-a-new-connection.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the postgresql-python-define-a-new-connection.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.