How to Connect Python to a Database

Chapter 8
6 min read
17 reads

This guide takes you through how to install PostgreSQL on your computer and connect your Python code to it.

Part 1: Installing PostgreSQL & pgAdmin

1. Download and Install

  1. Download: Go to the PostgreSQL Windows Downloads and click the download icon below your Operating System.
  2. The Wizard: Run the installer. Stick to the defaults until you reach these specific screens:
  • Components: Ensure PostgreSQL Server, pgAdmin 4, and Command Line Tools are all selected.
  • Password: You will be asked for a password for the postgres user. Choose something simple (like password123) and write it down. This is your "Master Key."
  • Port: Keep it at 5432.
  • Locale: Select [Default locale].
  1. Finish: Uncheck the "Stack Builder" box at the end and click Finish.

2. The "Beginner's Secret" (The Path Variable)

To make your computer recognize PostgreSQL commands in the terminal, you should add it to your Environment Variables:

  1. Search Windows (search icon at the bottom left corner of your computer) for "Edit the system environment variables."
  2. Click Environment Variables > Under "System variables," find Path and click Edit.
  3. Click New and paste the path to your bin folder (usually: C:\Program Files\PostgreSQL\16\bin).
  4. Click OK on all windows.

Part 2: Setting Up the Data in pgAdmin 4

We can connect to and manage PostgreSQL from the terminal. However, this can be overwhelming and hides alot of things. For this session, we're going to use another software to interact with PostgreSQL. We're going to use pgAdmin as our control center. It can be a bit overwhelming at first, but follow these steps exactly:

1. Connect to the Server

  1. Open pgAdmin 4. If installing PostgreSQL from Part 1 skipped/failed to install pgAdmin, just download it from here and install it.
  2. In the left sidebar, double-click Servers.
  3. Enter the credentials you created during installation.

2. Create the Database

  1. Right-click on Databases > Create > Database...
  2. Name the database foods.
  3. Click Save.

3....

Want to support this author?

By unlocking the full story, you directly support local writers. You'll also be able to track your reads, and discover amazing content!

How to Connect Python to a Database - SELF TAUGHT COMPUTER SCIENCE | Soma