CRUD Operations on Postgres using Async Database In Python
CRUD stands for Create, Read, Update and Delete Operations. All these Operations can be made Asynchronous using the Async Database Connection. After making Async Connection to Postgres Database, the performance of the Application improves significantly as all the operations are performed Concurrently rather than in a sequential manner. The Async database support in python is provided by Databases Library.
Databases is a python library which gives asyncio support for various databases including PostgreSQL, MySQL, and SQLite. SQLAlchamey- the Object Relationship Mapper can be added on this Databases layer to query the database. This database support can also be integrated with any async Web-Framework for communicating with Database .
Install Databases: Run the following pip command on the terminal.
pip install databases
Install Postgresql Database Driver: Run the following pip command on the terminal.
pip install databases[postgresql]
CRUD Operations :
Initially, before we perform any operation on Database it is important to connect to database as well as set up the connection. Connecting to the database using the async function :
In the database URL, you will have to substitute the username, password, host and database for your database
Connected to Database Disconnecting from Database
Create(C) : After Successful Connection to the database Let’s create a table named GfgExample using :
Connected to Database Created Table GfgExample Successfully Disconnecting from Database
Insert(I) : Now after Creation of GfgExample Table let’s insert values to it using Insert query:
Connected to Database Inserted values in GfgExample Table Successfully Disconnecting from Database
Read(R): Now, after Insertion of values in GfgExample Table, let’s read them using Select Statement :
Connected to Database Read the values in GfgExample Table Successfully Printing Id Values Fetched from GfgExample Table 1 2 Disconnecting from Database
Delete(D): Deleting all the Records from GfgExample Table :
Connected to Database Deleted All Records For GfgExample Successfully Disconnecting from Database
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course