Welcome to Day 2 of 12 Days of DigitalOcean! Yesterday, we started building our Birthday Reminder Service—a simple app that sends SMS notifications for upcoming birthdays. 🎉 We set up a PostgreSQL database on DigitalOcean to store contact details.
Today, we’ll connect to that database using Python and set up our project to keep sensitive credentials safe.
By the end of this post, you’ll have a Python script that securely fetches data from your database and is ready to scale when we host it on DigitalOcean.
Setting up the database was just the beginning. To build any meaningful app, we need a way to interact with that data programmatically. Python makes it easy to connect to PostgreSQL databases, and with the help of a library like pg8000, we can work with PostgreSQL databases in just a few lines of code.
To keep things secure, we’ll store our database credentials in a .env
file and load them into our script using python-dotenv. This ensures your credentials aren’t hard-coded into the script, making it safer to share and deploy your app.
Here’s the plan for today:
.env
file.python-dotenv
to load those credentials into your script.pg8000
contacts
tableBy the end of this, you’ll have a solid foundation for building the app’s logic.
Before we dive in, here’s what you’ll need:
To connect Python to PostgreSQL and keep our credentials secure, we’ll use two key libraries:
.env
file, so you don’t have to hardcode them in your script.Let’s install them now. Run this command in your terminal:
pip install pg8000 python-dotenv
Pro Tip: If you’re using a virtual environment (always a good idea!), make sure to activate it before running the above command to keep your dependencies organized.
In your project directory, create a file named .env. This is where we’ll store our database credentials. Add the following:
DB_HOST=<your-hostname>
DB_NAME=<your-database-name>
DB_USER=<your-username>
DB_PASSWORD=<your-password>
Replace the placeholder values with the credentials from Day 1.
Pro Tip: Add .env
to your .gitignore
file to ensure your credentials aren’t accidentally pushed to version control.
Create a new file called connect_to_db.py
, and set up the script to load credentials from .env
using python-dotenv
, and connect to our database.
Here’s the code to get started:
# connect_to_db.py
import pg8000
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
# Database connection details
DB_HOST = os.getenv("DB_HOST")
DB_NAME = os.getenv("DB_NAME")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_PORT = int(os.getenv("DB_PORT"))
try:
# Connect to the database
connection = pg8000.connect(
host=DB_HOST,
database=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
port=DB_PORT
)
print("Connection successful!")
except Exception as e:
print("An error occurred while connecting to the database:", e)
finally:
if connection:
connection.close()
This script does a few important things:
.env
file.pg8000.connect()
.Now, let’s make sure everything works. Run your script:
python connect_to_db.py
If everything is set up correctly, you should see:
Connection successful!
If there’s an error:
Now, let’s extend the script to fetch data. Update your connect_to_db.py
script to include the following:
# connect_to_db.py
import pg8000
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
# Database connection details
DB_HOST = os.getenv("DB_HOST")
DB_NAME = os.getenv("DB_NAME")
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_PORT = int(os.getenv("DB_PORT"))
try:
# Connect to the database
connection = pg8000.connect(
host=DB_HOST,
database=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
port=DB_PORT
)
print("Connection successful!")
# Query the database
cursor = connection.cursor()
query = "SELECT * FROM contacts;"
cursor.execute(query)
records = cursor.fetchall()
# Print the results
print("Contacts:")
for record in records:
print(record)
# Close the cursor and connection
cursor.close()
connection.close()
except Exception as e:
print("An error occurred:", e)
This script now:
Note: If the table is empty, no worries! You can still check that the script runs without errors. For testing, you can quickly add a sample contact by opening your database using psql
(or your preferred tool) and running this SQL command:
INSERT INTO contacts (first_name, last_name, birthday)
VALUES ('Test', 'User', '1990-01-01');
If you need a refresher on how to use psql or want to explore UI tools like pgAdmin or TablePlus, check out the instructions in Day 1.
Here’s what you accomplished today:
✅ Installed the required Python libraries.
✅ Connected to your DigitalOcean PostgreSQL database using Python.
✅ Fetched data from the contacts
table with a simple query.
Up next: Tomorrow, we’ll start adding logic to find upcoming birthdays and send SMS notifications using Twilio. This is where the app starts to come alive—stay tuned! 🚀
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!