Connect to PostgreSQL database in Python
Open new Postgresql database connection, credentials are automatically loaded from .env file. To edit the credentials add them in define new connection recipe.
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.
All required packages are automatically imported by MLJAR Studio for you so you don't have to worry about them.
# import packages
import psycopg
import os
from dotenv import load_dotenv
You can use this recipe as a test for your connection. If turn on check connection you will see credentials are incorrect you will see an error.
# load credentials from .env file:
load_dotenv(override=True)
# get the credentials
def create_new_connection():
try:
conn = psycopg.connect(
dbname=os.getenv("POSTGRES_DB_NAME"),
user=os.getenv("POSTGRES_USERNAME"),
password=os.getenv("POSTGRES_PASSWORD"),
host=os.getenv("POSTGRES_HOST"),
port=os.getenv("POSTGRES_PORT"),
)
# display connection status
print("Connection status: " + conn.info.status.name)
return conn
# check for errors
except psycopg.Error as e:
raise psycopg.Error(f"""
Error occurred while establishing connection:
{e}
Maybe you provided wrong credentials, use define new connection recipe to edit them.
Other option is that database server is down or you dont have the right acces to this database.
""")
# open new connection:
conn = create_new_connection()
Conclusions
Now you are ready to perform any database operation. Use one of out recipes to perform common tasks, or write a custom query in Raw query recipe unlocking full potential of SQL!
Recipes used in the postgresql-python-connect-to-database.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-connect-to-database.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.
psycopg>=3.2.1
python-dotenv>=1.0.1
Similar notebooks
List of similar Python notebooks, so you can find more inspiration ๐
Define a new PostgreSQL connection in Python
Connect to PostgreSQL database in Python
Show tables from PostgreSQL database
Show columns from table in PostgreSQL
Create new table using python and PostgreSQL
Drop table using Python and PostgreSQL
Backup table using python
Update column in table using Python
Select every column from table using python
Insert row into a table using Python
Run raw SQL query in python
Raw SQL query straight to pandas dataframe
From database to chart plotting
Update selected rows of a column in table ...
Fill PostgreSQL database with AI using Python
Transfer data from database to a Google sheet