PostgreSQL Tutorial

  • Home
  • Stored Procedures
  • Triggers
  • Views
  • Interfaces
    • PostgreSQL PHP
    • PostgreSQL Python
    • PostgreSQL JDBC
  • Functions
    • Aggregate Functions
    • Date / Time Functions
    • String Functions
    • Math Functions
Home / PostgreSQL Python / PostgreSQL Python: Connect To PostgreSQL Database Server

PostgreSQL Python: Connect To PostgreSQL Database Server

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.

1
CREATE DATABASE suppliers;

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:

1
conn = psycopg2.connect("dbname=suppliers user=postgres password=postgres")

Or you can use a list of keyword arguments:

1
conn = psycopg2.connect(host="localhost",database="suppliers", user="postgres", password="postgres")

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:

1
2
3
4
5
[postgresql]
host=localhost
database=suppliers
user=postgres
password=postgres

The following config() function read the database.ini file and returns the connection parameters. We put the config() function in the config.py file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/python
from configparser import ConfigParser
 
 
def config(filename='database.ini', section='postgresql'):
    # create a parser
    parser = ConfigParser()
    # read config file
    parser.read(filename)
 
    # get section, default to postgresql
    db = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))
 
    return db

The following connect() function connects to the suppliers database and prints out the PostgreSQL database version.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/python
import psycopg2
from config import config
 
def connect():
    """ Connect to the PostgreSQL database server """
    conn = None
    try:
        # read connection parameters
        params = config()
 
        # connect to the PostgreSQL server
        print('Connecting to the PostgreSQL database...')
        conn = psycopg2.connect(**params)
        # create a cursor
        cur = conn.cursor()
        
# execute a statement
        print('PostgreSQL database version:')
        cur.execute('SELECT version()')
 
        # display the PostgreSQL database server version
        db_version = cur.fetchone()
        print(db_version)
      
    # close the communication with the PostgreSQL
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
            print('Database connection closed.')
 
 
if __name__ == '__main__':
    connect()

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 the cursor and connection 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:

1
2
Connecting to the PostgreSQL database...
could not translate host name "localhosts" to address: Unknown host

The following displays error message when we change the database to a non-existing one: supplier

1
2
Connecting to the PostgreSQL database...
FATAL: database "supplier" does not exist

If we change the user to  postgress, it will not be authenticated successfully as shown below:

1
2
Connecting to the PostgreSQL database...
FATAL: password authentication failed for user "postgress"

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.

Related Tutorials

  • PostgreSQL Python: Create Tables
  • PostgreSQL Python: Insert Data Into a Table
  • PostgreSQL Python: Update Data in a Table
  • Connect To a PostgreSQL Database
  • PostgreSQL Python: Transaction
  • PostgreSQL Python: Handling BLOB Data
  • PostgreSQL Python: Querying Data
  • PostgreSQL Python: Delete Data from Tables
  • PostgreSQL Python: Call PostgreSQL Stored Procedures
  • Was this tutorial helpful ?
  • Yes   No
Next Tutorial: PostgreSQL Python: Create Tables

PostgreSQL Quick Start

  • What is PostgreSQL?
  • Install PostgreSQL
  • Connect to Database
  • Download PostgreSQL Sample Database
  • Load Sample Database
  • Explore Server and Database Objects

PostgreSQL Python

  • Connect To PostgreSQL Database
  • Create Tables in Python
  • Insert Data Into Table in Python
  • Update Data in Python
  • Query Data in Python
  • Handle Transactions in Python
  • Call PostgreSQL Stored Procedures in Python
  • Working with BLOB Data in Python
  • Delete Data from Tables in Python

About PostgreSQL Tutorial

PostgreSQLTutorial.com is a website dedicated to developers and database administrators who are working on PostgreSQL database management system.

We constantly publish useful PostgreSQL tutorials to keep you up-to-date with the latest PostgreSQL features and technologies. All PostgreSQL tutorials are simple, easy-to-follow and practical.

Recent PostgreSQL Tutorials

  • PostgreSQL CUBE
  • PostgreSQL GROUPING SETS
  • PostgreSQL ROLLUP
  • PostgreSQL FETCH
  • PostgreSQL Identity Column
  • PostgreSQL CREATE TABLE AS
  • PostgreSQL SELECT INTO
  • PostgreSQL ALL Operator
  • PostgreSQL Self-Join
  • PostgreSQL Alias

More Tutorials

  • PostgreSQL Cheat Sheet
  • PostgreSQL Administration
  • PostgreSQL PHP
  • PostgreSQL Python
  • PostgreSQL JDBC
  • PostgreSQL Resources

Site Info

  • Home
  • About Us
  • Contact Us
  • Privacy Policy

Copyright © 2018 by PostgreSQL Tutorial Website. All Rights Reserved.

⤒