Get started PostgreSQL
The PostgreSQL can be integrated with Python using psycopg2 module.
If you do not have it installed on your machine then you can use yum command to install it as follows:
pip install psycopg2
PIP is most likely already installed in your Python environment.
Test PostgreSQL Connection
To test if the installation was successful, or if you already have " psycopg2 " installed, create a Python page with the following content:
import psycopg2 #if this page is executed with no errors, you have the "psycopg2" module installed.
C:\Users\Your Name>python check_psycop2.py
If the above code was executed with no errors, " psycopg2 " is installed and ready to be used.
Start by creating a connection to the database.
import psycopg2 conn = psycopg2.connect(database = "books", user = "postgres", password = "pass1234", host = "localhost", port = "5432") print ("Opened database successfully")
C:\Users\Your Name>python demo_pgsql_connection.py Opened database successfully
Now you can start querying the database using SQL statements.
- user - The username you use to work with PostgreSQL, The default username for the PostgreSQL database is postgres.
- password - Password is given by the user at the time of installing the PostgreSQL.
- host - Host name is the server name or Ip address on which PostgreSQL is running. if you are running on localhost, then you can use localhost, or it’s IP i.e., 127.0.0.0
- database - Database name to which you want to connect. Here we are using Database named “books”.