Connect with Python API
Connect to your server using python scripts
Last updated
Connect to your server using python scripts
Last updated
You can also connect to your database and execute queries through PostgreSQL's Python API. We'll be using the python package psycopg2 to connect to our database in the following steps:
Create a database.ini
file containing sensitive information needed to connect to our database
Create a config.py
script containing a config function
Create and run a connect_to_db.py
script to connect to the database
I relied heavily on this website for the information on this page:
To connect to your database, you first need to provide Python your credentials. If you're sharing project code with team, or if your code is in a public repository, you don't want to share your host name, username, and (most importantly) password with everyone who sees the Python scripts that run queries.
Instead, we can write all of our login credentials in a file titled database.ini
and refer to it in our config.py
script. Additionally, if you're using a GitHub repository to share project code, we can add database.ini
to our .gitignore file so that our personal login information is not contained in the script.
In your folder where you will place all your Python scripts with queries (meaning the script will require you to connect to your database), write a database.ini
file that contains the following information:
To set your configurations for connecting to your database in Python, create a config.py
file with a function called config, which you will be using whenever you want to connect to your database in your scripts. (2)
Place this code in a script titled config.py
:
Now, we will run a function called "connect()" to test whether we can connect to our database.
Place the following code in a script called connect_to_db.py
:
Run connect_to_db.py
in your terminal:
Your output should be a variation of the following
If you see the above output, then you've successfully connected to your database!
If you want to learn more about creating table and executing other queries using the Python API, the following documentation, which I also referenced throughout this section, has tutorials and examples on creating table and executing other queries using psycopg2.
Also, the following Medium post also discusses how to use pandas to create dataframes from tables in your database (towards the end of the post).