![]() |
VOOZH | about |
Psycopg is the most popular PostgreSQL adapter used in Python. Its works on the principle of the whole implementation of Python DB API 2.0 along with the thread safety (the same connection is shared by multiple threads). It is designed to perform heavily multi-threaded applications that usually create and destroy lots of cursors and make a large number of simultaneous INSERTS or UPDATES. Psycopg features client-side and server-side cursors, asynchronous communication, and notification. Psycopg 2 is both Unicode and Python 3 friendly.
The current psycopg2 implementation supports:
For most of the available Operating Systems, the quickest way to install this package is through the wheel package available inthe PyPI library. We must make sure that we use the latest version of pip, which can be updated using the following command in the terminal.
$ pip install -U pip $ pip install psycopg2-binary
This will install the pre-compiled binary version of the module which doesn't require the built or runtime prerequisites. Then we can import the psycopg2 package in the usual manner:
The basic use of Psycopg is in implementing the DB API 2.0 protocol to all the database adapters. Here is the basic interactive session of the basic commands.
Example 1: Program to establish a connection between python program and a PostgreSQL database.
Example 2: Creating a table using python
Example 3: Inserting data into the table:
Python variables are converted to SQL values with Psycopg, Python determines the function used to convert the object into a string representation suitable for PostgreSQL.Passing parameters to an SQL statement happens in functions such as cursor.execute() by using %s as the placeholder into the SQL statement.
Example 4: Fetching the data from the database and displaying it into the terminal.
Example 5: Updating the data in the database.
Example 6: Deleting data from the database.