-1

A similar question was asked for Java, however as far as I know Python does not really supports multiple threads being executed concurrently because of the GIL.

In cx_Oracle, it seems to be considered bad practice to implement the db connection as a Singleton, with code like this:

# "con" would be a global variable, or a class member
def get_connection():
    if not con:
        con = cx_Oracle.Connection('...connecton details')
    return con

I saw that cx_Oracle also offers the possibility to do connection pooling, which seems a better option to me.

When using a db connection object in Python with cx_Oracle, what are the pros and cons among the possible approaches?

E.g. :

  • Single global variable (no singleton)
  • Single DB connection with singleton pattern
  • Connection pooling
  • Opening/Closing a new connection on any new DB request

How can one decide on which approach to chose?

Thanks

Carmellose
  • 4,815
  • 10
  • 38
  • 56

1 Answers1

1

If you have a single thread in your application (or multiple threads but only a single thread ever accesses the database), a singleton connection or single global variable is sufficient. As soon as you have multiple threads in your application that need to access the database concurrently, multiple connections are necessary. The Oracle client software does not permit concurrent access of the database through a single connection. It will instead serialize those accesses. The cx_Oracle driver does support concurrent access through multiple connections, however. For those situations a SessionPool is the best option. As Chris mentioned, ensure that threaded=True is used when creating the pool.

Anthony Tuininga
  • 6,388
  • 2
  • 14
  • 23