CodeByte
Published in

CodeByte

How to connect and run PostgreSQL queries using Python

Photo by Caspar Camille Rubin on Unsplash

Consider you are working on a python application that needs to communicate with a Postgres database and you want to run SQL queries from the python application itself.

If you are working with a web application, using an object-relational mapper (ORM) would be the right and efficient way to go. But, working this way would also work if you don’t mind writing SQL queries or if you have only simple queries to run and don’t really need an ORM. Here’s how you can easily do it.

First, we’ll need to install Psycopg2:

pip install psycopg2-binary

Here are the steps:

  • Import libraries, we’ll use environment variables for database credentials.
  • Connect to the database.
  • Create a cursor from the connection
  • Generate the SQL query
  • Execute the query using the cursor we created
  • Commit the changes
  • Close the cursor
  • Close the connection

See the above steps in code here:

The above steps and code are enough to communicate with the database using python. You can easily process the result stored using python’s JSON library.

Stay tuned for a similar article where I’ll build a set of functions that automatically creates SQL queries and does all the database operations based on some functional arguments.

Explore and Follow Codebyte.

Happy Coding….

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Devashish Patil

Devashish Patil

Cloud Engineer at Google | IITR Alumnus