Summary: in this tutorial, you will learn how to connect to the PostgreSQL database server in Python program using psycopg database adapter.
The following statement creates a new database named suppliers
in the PostgreSQL database server.
To connect to the suppliers
database, you use the connect()
function of the psycopg2
module. The connect()
function creates a new database session and returns a new instance of the connection
class.
With a connection
object, you can create a new cursor
to execute an SQL statement and terminate a transaction using either commit()
or rollback()
method.
You can specify the connection parameters as a string and pass it to the connect()
function as follows:
Or you can use a list of keyword arguments:
The following is the list of the connection parameters:
- database: the name of the database that you want to connect.
- user: the username used to authenticate.
- password: password used to authenticate.
- host: database server address e.g., localhost or an IP address
- port: the port number that defaults to 5432 if it is not provided.
To make it more convenient, we will use a configuration file to store all connection parameters. The following is the content of the database.ini
file:
The following config()
function read the database.ini
file and returns the connection parameters. We put the config()
function in the config.py
file:
The following connect()
function connects to the suppliers
database and prints out the PostgreSQL database version.
How it works.
- First, read database connection parameters from the
database.ini
file. - Next, create a new database connection by calling the
connect()
function. - Then, create a new
cursor
and execute an SQL statement to get the PostgreSQL database version. - After that, read the result set by calling the
fetchone()
method of the cursor object. - Finally, close the communication with the database server by calling the
close()
method of thecursor
andconnection
objects.
The connect()
function raises the DatabaseError
exception if an error occurred. To see how it works, we can change the connection parameters in the database.ini
file.
For example, if we change the host to localhosts
, the program will output the following message:
The following displays error message when we change the database to a non-existing one: supplier
If we change the user to postgress
, it will not be authenticated successfully as shown below:
In this tutorial, we have shown you how to connect to the PostgreSQL database server in Python. We will reuse the config()
function in the subsequent tutorial.