PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Databases » Python PostgreSQL Tutorial Using Psycopg2

Python PostgreSQL Tutorial Using Psycopg2

Updated on: March 9, 2021 | Python Tags: Databases Python

TweetF  sharein  shareP  Pin

This Python PostgreSQL tutorial demonstrates how to use the Psycopg2 module to connect to PostgreSQL and perform SQL queries, database operations. There are many ways we can connect to a PostgreSQL database from Python, and in this tutorial, we’re going to explore several options to see how to achieve this.

Below is the list of available Python modules to work with the PostgreSQL database server.

  • Psycopg2
  • pg8000
  • py-postgresql
  • PyGreSQL
  • ocpgdb
  • bpgsql
  • SQLAlchemy. SQLAlchemy needs any of the above to be installed separately.

Note: Above all modules adhere to Python Database API Specification v2.0 (PEP 249). This API is designed to encourage and maintain the similarity between the Python database modules to access databases. In other words, the syntax, method, and way of access the database are the same in all the above modules.

We stick to the Psycopg2 because it is arguably the most popular and stable module to work with PostgreSQL. Also, We are using Psycopg2 to work with PostgreSQL because of the following reasons.

  • It is used in most of the Python and Postgres frameworks.
  • It is also actively maintained and supports Python’s primary version, i.e., Python 3 and Python 2.
  • It is thread-safe and designed for heavily multi-threaded applications. Note, threads can share the connections.

This Python PostgreSQL guide mainly focuses on the followings

  • Installing Psycopg2 and use its API to access the PostgreSQL database
  • Perform data insertion, data retrieval, data update, and data deletion through Python application.
  • Next, it will cover PostgreSQL transaction management, connection pooling, and error-handling techniques to develop robust Python programs with PostgreSQL.

Let’s dive right in.

Table of contents

  • Install Psycopg2 using the pip command
    • Verify Psycopg2 installation
  • Python PostgreSQL database connection
    • Python example to connect PostgreSQL database
    • Important points
  • Create a PostgreSQL table from Python
  • The mapping between Python and PostgreSQL types
    • Constants and numeric conversion
  • Perform PostgreSQL CRUD operations from Python
  • Working with PostgreSQL date and time in Python
  • Call PostgreSQL Function and Stored Procedure from Python
  • Python PostgreSQL Transaction management
  • Python PostgreSQL Connection Pooling
  • Python PostgreSQL Exercise Project

Install Psycopg2 using the pip command

You need to install the current version of Psycopg2 (2.8.6) on your machine to use PostgreSQL from Python. This module is available on pypi.org.

Using the following pip command, you can install Psycopg2 on any operating system, including Windows, macOS, Linux, Unix, and Ubuntu.

pip install psycopg2

You can also install a specific version using the following command.

pip install psycopg2=2.8.6

If you are facing pip install error like “connection error:  [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)”. You can resolve this error by setting pypi.org and files.pythonhosted.org as trusted hosts. If you are facing a pip install error Please try following the command.

python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org psycopg2

The current psycopg2 module supports:

  • Python version 2.7, and Python 3 versions from 3.4 to 3.8
  • PostgreSQL server versions from 7.4 to 12
  • PostgreSQL client library version from 9.1

Verify Psycopg2 installation

You should get the following messages after running the above command.

  • Collecting psycopg2
  • Downloading psycopg2-2.8.6
  • Installing collected packages: psycopg2
  • Successfully installed psycopg2-2.8.6

Please use the following command to install Psycopg2 If you are using anaconda.

conda install -c anaconda psycopg2

Python PostgreSQL database connection

In this section, we will learn how to connect to PostgreSQL through Python using Psycopg2.

Arguments required to connect PostgreSQL database from Python

You need to know the following detail of the PostgreSQL server to perform the connection.

  • Username: 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 Name: This is the server name or Ip address on which PostgreSQL is running. if you are running on localhost, then you can use localhost, or its IP, i.e., 127.0.0.0
  • Database Name: Database name to which you want to connect. Here we are using Database named “postgres_db“.

How to Connect to PostgreSQL in Python

  1. Install Psycopg2 module

    Install and import psycopg2 module. Import using a import psycopg2 statement so you can use this module’s methods to communicate with the PostgreSQL database.

  2. Use the connect() method

    Use the psycopg2.connect() method with the required arguments to connect MySQL. It would return an Connection object if the connection established successfully

  3. Use the cursor() method

    Create a cursor object using the connection object returned by the connect method to execute PostgreSQL queries from Python.

  4. Use the execute() method

    The execute() methods run the SQL query and return the result.

  5. Extract result using fetchall()

    Use cursor.fetchall() or fetchone() or fetchmany() to read query result.

  6. Close cursor and connection objects

    use cursor.clsoe() and connection.clsoe() method to close PostgreSQL connections after your work completes

Python PostgreSQL connection to access database
Python PostgreSQL connection to access database

Python example to connect PostgreSQL database

To connect the PostgreSQL database and perform SQL queries, you must know the database name you want to connect to, and if you have not created any database, I advise you to create one before proceeding further.

import psycopg2
from psycopg2 import Error

try:
    # Connect to an existing database
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    # Create a cursor to perform database operations
    cursor = connection.cursor()
    # Print PostgreSQL details
    print("PostgreSQL server information")
    print(connection.get_dsn_parameters(), "\n")
    # Executing a SQL query
    cursor.execute("SELECT version();")
    # Fetch result
    record = cursor.fetchone()
    print("You are connected to - ", record, "\n")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

You should get the following output after connecting to PostgreSQL from Python

PostgreSQL server information
{'user': 'postgres', 'dbname': 'python_db', 'host': '127.0.0.1', 'port': '5432', 'tty': '', 'options': '', 'sslmode': 'prefer', 'sslcompression': '0', 'krbsrvname': 'postgres', 'target_session_attrs': 'any'} 

You are connected to -  ('PostgreSQL 12.2) 
PostgreSQL connection is closed

Important points

  • In our example, we are executing a SELECT version(); query to fetch the PostgreSQL version.
  • Using the Error class of Psycopg2, we can handle any database error and exception while working with PostgreSQL from Python. Using this approach, we can make our application robust.
  • The error class helps us to understand the error in detail. It returns an error message and error code if any.
  • We can create as many cursors as we want from a single connection object. Cursors created from the same connection are not isolated, i.e., any changes done to the database by a cursor are immediately visible by the other cursors.
  • Cursors are not thread-safe.
  • We can retrieve query result using cursor methods such as fetchone(), fetchmany(), fetcthall().

try-except-finally block

  • We placed all our code in the try-except block to catch the database exceptions and errors that may occur during this process.

cursor.close()  and connection.close()

  • It is always good practice to close the cursor and connection object once your work gets completed to avoid database issues.

Create a PostgreSQL table from Python

This section will learn how to create a table in PostgreSQL from Python. In this example, we will create a “Mobile” table in PostgreSQL.

import psycopg2
from psycopg2 import Error

try:
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    cursor = connection.cursor()
    # SQL query to create a new table
    create_table_query = '''CREATE TABLE mobile
          (ID INT PRIMARY KEY     NOT NULL,
          MODEL           TEXT    NOT NULL,
          PRICE         REAL); '''
    # Execute a command: this creates a new table
    cursor.execute(create_table_query)
    connection.commit()
    print("Table created successfully in PostgreSQL ")

except (Exception, Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

Output

Table created successfully in PostgreSQL PostgreSQL connection is closed
Create a PostgreSQL table from Python
Create a PostgreSQL table from Python

Note: Note: In the end, we are committing our changes to the database using the commit() method.

The mapping between Python and PostgreSQL types

There is default mapping specified to convert Python types into PostgreSQL equivalent, and vice versa. Whenever you execute a PostgreSQL query using Python following table is used by psycopg2 to return the result in the form of Python objects.

PythonPostgreSQL
NoneNULL
boolbool
floatreal or double
intsmallint
integer
bigint
Decimalnumeric
strvarchar
text
datedate
timetime
timetz
datetimetimestamp
timestamptz
timedeltainterval
listARRAY
tupleComposite types
IN syntax
dicthstore

Constants and numeric conversion

When you try to insert Python None and boolean values such as True and False into PostgreSQL, it gets converted into the proper SQL literals. The same case is with Python numerical types. It gets converted into equivalent PostgreSQL types.

For example, When you execute an insert query, Python numeric objects such as int, long, float, Decimal are converted into a PostgreSQL numerical representation. When you read from the PostgreSQL table, integer types are converted into an int, floating-point types are converted into a float, numeric/Decimal are converted into Decimal.

Perform PostgreSQL CRUD operations from Python

Now, we created a “mobile” table. Now let’ see how to perform insert, select, update, and delete PostgreSQL queries from Python.

In this section, We will learn how to perform PostgreSQL CRUD operations from Python.

Now, Let’s see the example.

import psycopg2

try:
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    cursor = connection.cursor()
    # Executing a SQL query to insert data into  table
    insert_query = """ INSERT INTO mobile (ID, MODEL, PRICE) VALUES (1, 'Iphone12', 1100)"""
    cursor.execute(insert_query)
    connection.commit()
    print("1 Record inserted successfully")
    # Fetch result
    cursor.execute("SELECT * from mobile")
    record = cursor.fetchall()
    print("Result ", record)

    # Executing a SQL query to update table
    update_query = """Update mobile set price = 1500 where id = 1"""
    cursor.execute(update_query)
    connection.commit()
    count = cursor.rowcount
    print(count, "Record updated successfully ")
    # Fetch result
    cursor.execute("SELECT * from mobile")
    print("Result ", cursor.fetchall())

    # Executing a SQL query to delete table
    delete_query = """Delete from mobile where id = 1"""
    cursor.execute(delete_query)
    connection.commit()
    count = cursor.rowcount
    print(count, "Record deleted successfully ")
    # Fetch result
    cursor.execute("SELECT * from mobile")
    print("Result ", cursor.fetchall())


except (Exception, psycopg2.Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

Output:

1 Record inserted successfully
Result  [(1, 'Iphone12', 1100.0)]
1 Record updated successfully 
Result  [(1, 'Iphone12', 1500.0)]
1 Record deleted successfully 
Result  []
PostgreSQL connection is closed

Please refer to the following tutorials to have more information on insert, update, and delete data from the PostgreSQL table using Python.

In the following tutorial, we will teach you how to pass parameters to SQL queries.  We will learn how to use a parameterized query to pass Python variables and dynamic data into SQL queries.

  • Insert data into the PostgreSQL Table from Python: Learn how to execute the SQL insert query from a Python application to add a record to the PostgreSQL table.
  • Select data from PostgreSQL Table from Python: Learn how to execute a SQL select query from a Python application to fetch rows from the database table. We will also learn how to use fetchall(), fetchmany() and fetchone() methods to read a limited number of rows from the table.
  • Update data of PostgreSQL table from Python: Learn how to execute SQL update query from Python application to modify a PostgreSQL table’s records.
  • Delete data from PostgreSQL table from Python: Learn how to execute SQL delete query from Python application to delete records from a PostgreSQL table.

Working with PostgreSQL date and time in Python

This section will demonstrate how to work with PostgreSQL date and timestamp data types in Python and vice-versa. Most of the time, we work with date and time data. We insert date and time into the table and also read from it in our application whenever required.

In a usual scenario, when you execute the insert query with the datetime object, the Python psycopg2 module converts it into a PostgreSQL timestamp format to insert it in the table.

And when you execute a SELECT query from Python to read timestamp values from the PostgreSQL table, the psycopg2 module converts it into a datetime object.

We are using the “Item” table for this demo. Please copy and execute the below query on your PostgreSQL query tool to have adequate data for this operation.

CREATE TABLE item ( 
	item_id serial NOT NULL PRIMARY KEY, 
	item_name VARCHAR (100) NOT NULL, 
	purchase_time timestamp NOT NULL,
	price INTEGER NOT NULL
);

Let’s understand this scenario with a simple example. Here we will read purchase_time column from the PostgreSQL table and convert it into a Python datetime object.

import datetime

import psycopg2

try:
    connection = psycopg2.connect(user="postgres",
                                  password="pynative@#29",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres_db")

    cursor = connection.cursor()
    # Executing a SQL query to insert datetime into table
    insert_query = """ INSERT INTO item (item_Id, item_name, purchase_time, price) VALUES (%s, %s, %s, %s)"""
    item_purchase_time = datetime.datetime.now()
    item_tuple = (12, "Keyboard", item_purchase_time, 150)
    cursor.execute(insert_query, item_tuple)
    connection.commit()
    print("1 item inserted successfully")

    # Read PostgreSQL purchase timestamp value into Python datetime
    cursor.execute("SELECT purchase_time from item where item_id = 12")
    purchase_datetime = cursor.fetchone()
    print("Item Purchase date is  ", purchase_datetime[0].date())
    print("Item Purchase time is  ", purchase_datetime[0].time())

except (Exception, psycopg2.Error) as error:
    print("Error while connecting to PostgreSQL", error)
finally:
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

Output:

1 item inserted successfully
Item Purchase date is   2020-12-14
Item Purchase time is   12:47:45.854942
PostgreSQL connection is closed

Call PostgreSQL Function and Stored Procedure from Python

PostgreSQL function and the Stored procedure can perform different operations, such as data manipulation or data retrieval. We can execute such functions from Python.

Learn how to execute the PostgreSQL function and Stored procedure in Python.

Python PostgreSQL Transaction management

In this article, we will see how to manage PostgreSQL transactions from Python using psycopg2.

  • Learn how to use the commit() and the rollback() method of a connection class to manage database transactions and maintain the ACID properties.
  • Also, learn how to change the PostgreSQL transaction isolation level from Python.

Python PostgreSQL Connection Pooling

This section will let you know what a connection pool is and how to implement a PostgreSQL database connection pool using Psycopg2 in Python. Using Psycopg2, we can implement a connection pool for simple as well as multithreaded applications.

Use the Connection pool to increase the speed and performance of database-centric applications.

Python PostgreSQL Exercise Project

Solve our free Python database exercise project to practice and master the PostgreSQL database operations using Python.

In this exercise project, We will implement the Hospital Information System, which covers all database operations. In this Python database exercise, we will do database CRUD operations From Python. This practice exercise also covers transaction management and error-handling techniques.

Reference:

  • Psycopg2
  • PostgreSQL
  • PEP 249

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Databases Python

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

35 Comments

Comments

  1. Md.Parvez Alam says

    September 15, 2020 at 7:01 pm

    So the connection pool should not be closed in each function calling to execute the query.

    so how should we reuse the connection pool second time user trying to connect the database..

    Reply
  2. jack says

    August 29, 2020 at 4:22 pm

    File "verbinding.py", line 1, in 
        import psycopg2
      File "/home/scripts/postgresql/psycopg2.py", line 1
        Connecting to a Database
        SyntaxError: invalid syntax
    
        My OS is Linux Opensuse 15.2

    This is my script.

        
        import psycopg2
    try:
        connection = psycopg2.connect(user = "jack",
                                      password = "xxxxxxx",
                                      host = "127.0.0.1",
                                      port = "5432",
                                      database = "contacten")
    
        cursor = connection.cursor()
        # Print PostgreSQL Connection properties
        print ( connection.get_dsn_parameters(),"\n")
    
        # Print PostgreSQL version
        cursor.execute("SELECT version();")
        record = cursor.fetchone()
        print("You are connected to - ", record,"\n")
    
    except (Exception, psycopg2.Error) as error :
        print ("Error while connecting to PostgreSQL", error)
    finally:
        #closing database connection.
            if(connection):
                cursor.close()
                connection.close()
                print("PostgreSQL connection is closed")

    What is wrong?

    Reply
  3. chaithanya says

    July 31, 2020 at 6:29 pm

    Hey Vishal, thanks for this, very nicely written. am a beginner and i could manage to understand and implement it..It was very helpful and suggested it to my friends..

    I have a doubt..

    Am automating website login -> OTP login -> so i made connection to DB and automated to read the OTP, now how can i stitch this peace of query with my python code with the whole website automation flow.. Please suggest..thanks in advance..

    Reply
  4. Prajakta says

    June 30, 2020 at 11:53 am

    Hi, Very helpful blog indeed.
    But how to connect to a specific schema in the database using psycopg2?
    Is there any parameter that can be used inside the connection string?

    Reply
    • Vishal says

      July 1, 2020 at 6:55 pm

      Hey Prajakta, You can pass the database name in the connection string.

      Reply
  5. Akshay says

    June 2, 2020 at 8:37 am

    Nice article Vishal. It’s really helpful.

    Reply
    • Vishal says

      June 4, 2020 at 12:23 pm

      Thank you, Akshay

      Reply
  6. mario says

    April 24, 2020 at 10:31 pm

    great article. Thank you, Vishal

    Reply
    • Vishal says

      April 26, 2020 at 5:03 pm

      You are welcome, Mario

      Reply
  7. charles says

    April 4, 2020 at 8:36 pm

    Hi Vishal,

    This was an excellent article and it taught me exactly what I needed to know. I really liked your coding technique and will copy your style going forward. Thanks so much for your knowledge. I have this site bookmarked now.

    Reply
    • Vishal says

      April 5, 2020 at 1:02 am

      Charles, I appreciate your kind words, Thank you.

      Reply
  8. Mehdi says

    January 30, 2020 at 2:53 am

    Hi every one,
    I have a question:
    I run my code just by one connection! I create a connection and don’t close it at all, but I create and close cursor every time that I run a query.
    Is there any problems with my code?
    Is this safe?

    class DBHelper:
        def __init__(self):
            self.connection = psycopg2.connect("***")
    
        def get_user_uuid(self, u_id):
            stmt = "SELECT uuid FROM users WHERE u_id=%s"
            args = (u_id,)
            try:
                with self.connection as conn:
                    with conn.cursor() as cur:
                        cur.execute(stmt, args)
                        return cur.fetchone()
            except Exception as e:
                print('WARNING DATABASE: ', e)
    
    Reply
  9. Dee says

    November 13, 2019 at 11:00 pm

    Hi,
    Can we connect to 2 different databases?
    I am using a SQL query to join 2 tables (in different databases) and want to make sure both databases are connected to give the output. Thanks

    Reply
  10. nikhil says

    November 11, 2019 at 9:40 pm

    Hi Vishal,
    really good article. i still have an issue with connecting postgresql12 from python3.8. I could resolve libssl1.1.dylib but unable to resolve libcrypto.1.1.dylib. what could be the issue.
    Error is –
    ImportError: dlopen(/Users/nikhilgumaste/venv/lib/python3.8/site-packages/psycopg2/_psycopg.cpython-38-darwin.so, 2): Library not loaded: libcrypto.1.1.dylib
    Referenced from: /Users/nikhilgumaste/venv/lib/python3.8/site-packages/psycopg2/_psycopg.cpython-38-darwin.so
    Reason: image not found

    Reply
  11. Sibasis Dash says

    July 23, 2019 at 6:25 pm

    Upon installing psycopg2 in the command prompt got the following error:
    (pip install psycopg2)
    Error:

    Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-_zpyb9xh/psycopg2/
    

    Try:
    pip install psycopg2-binary
    (as psycopg2 has been renamed from the release of version 2.8)

    Reply
  12. Simran bhavsar says

    July 18, 2019 at 11:49 am

    “python setup.py egg_info” failed with error code 1 in

    /private/var/folders/vn/480f5zh962ld8n47hxfl_zv80000gn/T/pip-install-qcqsa9kq/psycopg2/
    

    Getting this error when I try to install psycopg2 using above giving command for install it.

    Reply
  13. Brian P. Boberg says

    July 14, 2019 at 8:02 am

    Excellent article. I will refer back to this article, I am sure.

    Reply
  14. Val says

    July 4, 2019 at 8:13 am

    what if i want to query result from a database then insert the query result to another table in another database?

    Reply
    • Vishal says

      July 5, 2019 at 9:29 am

      Hi Val,

      • Create PostgreSQL connection (specify the first database name to connect) and read data keep that data in a list or any data structure. close database connection
      • Create new PostgreSQL connection (specify the second database name to connect) and read your list and execute insert query to insert data. close database connection
        Python PostgreSQL SELECT
        Python PostgreSQL CRUD
      Reply
  15. Robert McConnell says

    July 2, 2019 at 7:33 pm

    This looks like a good article and I plan to work through it, but the first step failed for me. I have PostgreSQL 10.2 installed on a dedicated server elsewhere on my home network, so there is no pg_config on this workstation. The binary version did install, and I can connect to the remote server, but you need to mention this option in the installation instructions.

    I’m having the same problem with the PHP pdo, but there is no binary option available for that one.

    Reply
  16. Gaurav says

    June 30, 2019 at 6:27 am

    Hey, I am working on a webapp, I need to get data from my client to my Postgres DB.

    How can I do that using a python script?
    Or else
    Is their a way where I can provide a python script to my client and they can run at their terminal to send data to my Server?

    Reply
  17. Dnyanada aw says

    May 7, 2019 at 11:17 am

    very nicely written detailed article . Thank you. !

    Reply
  18. Dnyanada aw says

    May 7, 2019 at 11:17 am

    very nicely written detailed article . Thank you.

    Reply
  19. Cary Hutchinson says

    February 5, 2019 at 3:36 am

    I cannot get a connection to Google PostgreSQL. Is there anything different I have to use for the host?

    Reply
    • Vishal says

      February 5, 2019 at 8:54 am

      Hey, Cary have you provided all the required arguments. Let me know the error you are getting.

      Reply
      • Cary Hutchinson says

        February 5, 2019 at 5:40 pm

        Exception has occurred: psycopg2.OperationalError
        could not connect to server: Connection timed out (0x0000274C/10060)   Is the server running on host "35.188.138.77" and accepting   TCP/IP connections on port 5432? 
          File "C:\Users\Cary\Documents\Programming\Python\psycopg2 Example.py", line 2, in 
            conn = psycopg2.connect(dbname = "postgres", user = "postgres", password = "6601-ssi", host = "35.188.138.77", sslmode='require')
        
        Reply
        • Vishal says

          February 6, 2019 at 6:50 am

          Hi, Cary A connection time out raises an OperationalError exception. change connection time-out value while connection to PostgreSQL.

          conn = psycopg2.connect(dbname = “postgres”, user = “postgres”, 
                                  password = “6601-ssi”, host = “35.188.138.77”, 
                                  sslmode=’require’, connect_timeout=3)
          

          Also, have you checked manually executing queries on PostgreSQL?

          Reply
        • George says

          February 8, 2019 at 1:52 pm

          Hi Cary,

          This is because the server is not reachable, may be there are security policies which are preventing the inbound connecting to the db server.
          Please check the inbound security policy at the db server.

          Thanks,
          George.

          Reply
  20. Mo says

    October 21, 2018 at 9:34 am

    This is really awesome! Thank you so much! Easy to follow and understand.

    Reply
    • Vishal says

      October 21, 2018 at 11:22 am

      Thank you! I am glad you liked it

      Reply
  21. Kerim says

    October 3, 2018 at 4:35 pm

    Well detailed and complete tutorial. Thank you very much!

    Reply
    • Vishal says

      October 3, 2018 at 9:01 pm

      Hey kerim, I am glad you liked it

      Reply
  22. mmmanmm says

    September 21, 2018 at 11:18 am

    should line 26 be handling tuple instead?

    Reply
  23. man says

    September 21, 2018 at 11:17 am

    in section Python Example to manage PostgreSQL transactions
    line 26, the record is a tuple. It should be converted by
    int(record(0))

    Reply
    • Vishal says

      September 21, 2018 at 4:21 pm

      No required here because we are fetching only single column I.e. balance.

      If you are fetching multiple columns then yes, we should fetch column with it’s index position

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

 Python PostgreSQL

  • Python PostgreSQL Guide
  • Python PostgreSQL Select
  • Python PostgreSQL CRUD
  • Python PostgreSQL call Function
  • Python PostgreSQL Transactions
  • Python PostgreSQL Connection Pool
  • Python Database Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python Regex Python Random Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON
TweetF  sharein  shareP  Pin

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Privacy Policy
  • Cookie Policy
  • Terms Of Use
  • Contact Us
DMCA.com Protection Status

Copyright © 2018-2021 · [pynative.com]