Establishing a connection to the PostgreSQL server
In order to establish a connection to the PostgreSQL server, we will make use of the pscopg2 library in python. You can install psycopg2 using the following command:
pip install psycopg2
After installing the library, the following code can be used to create a connection to the database server:
Python3
import psycopg2 def get_connection(): try : return psycopg2.connect( database = "postgres" , user = "postgres" , password = "password" , host = "127.0.0.1" , port = 5432 , ) except : return False conn = get_connection() if conn: print ( "Connection to the PostgreSQL established successfully." ) else : print ( "Connection to the PostgreSQL encountered and error." ) |
Running the above code will produce the following result if the database credentials provided is correct and the connection is successfully established:
Connection to the PostgreSQL established successfully.
Python Psycopg2 – Getting ID of row just inserted
In this article, we are going to see how to get the ID of the row just inserted using pyscopg2 in Python