python postgresql
Python hosting: Host, run, and code Python in the cloud!
Learn how to effectively utilize Python with the powerful PostgreSQL database. PostgreSQL, a robust relational database management system (RDBMS), boasts of features like foreign keys, joins, views, triggers, stored procedures, and much more. By the end of this guide, you’ll be familiar with the essentials of integrating PostgreSQL with Python.
Relevant Course: Master SQL Databases with Python
Setting Up PostgreSQL for Python
Install PostgreSQL
To commence, ensure you have both the PostgreSQL DBMS and the psycopg2
Python module. For those on an Ubuntu system, you can swiftly install the PostgreSQL using the following:
1 | sudo apt-get install postgresql postgresql-contrib |
To confirm the successful installation and running status of PostgreSQL, employ:
1 | sudo /etc/init.d/postgresql status |
If you’re not greeted with the expected screen, the commands below might come in handy:
1 | sudo service postgresql start |
Install psycopg2
Psycopg
serves as the bridge connecting Python to PostgreSQL. To get it on board, use:
1 | sudo apt-get install python-psycopg2 |
Next, set up a database and its user, also referred to as a role
, with these commands:
1 | sudo -u postgres createuser -D -A -P pythonspot |
A quick reload ensures everything is in order:
1 | sudo /etc/init.d/postgresql reload |
Python and PostgreSQL in Action
Creating Tables and Populating Them
Run the below script to create a database table and fill it with some initial data:
1 | #!/usr/bin/python |
It’s vital to execute all SQL queries for changes to take effect:
1 | con.commit() |
Reading Data
Fetch data using the SELECT SQL
command. The method returns a list for every data row:
1 | #!/usr/bin/python |
Updating Data
Modify data within a PostgreSQL table using the following:
1 | #!/usr/bin/python |
Deleting Data
Erase data from your PostgreSQL table using:
1 | #!/usr/bin/python |
Navigate through more Python database interactions: Back | Next
Leave a Reply: