Posts

Showing posts with the label PostgreSQL

Python and PostgreSQL: Create a PostgreSQL Database Connection Using a Config File

This technique can easily be applied to other databases. 1. pip install two packages if you do not already have them in your Python environment. (Search the internet for ‘python pip install’ if you need help.) A. psycopg2: To interact with PostgreSQL databases B. configparser: To interact with config files 2. Create a config file named config.ini. Paste in the text below: [ default] host = localhost db_name = your_database_name postgres_user = postgres_username postgres_password = your_password Edit the details to match your environment. 3. Create a Python file named main.py. Paste in the text below: from configparser import SafeConfigParser import psycopg2 parser = SafeConfigParser() parser.read('config.ini') host = parser.get('default', 'host') db_name = parser.get('default', 'db_name') postgres_user = parser.get('default', 'postgres_user') postgres_password = parser.get('default', 'po...