0

I have trouble with a database connection. I have a script that executes another script (below) 2000 times. I'm using pg database. I have set the limit number of connection to 5 maximum. But it look like there is more than 5 connections at same time because my cpu is running at 100% and in stats of my database that say I have more than 100 connections in same time.

So I'm wondering if the keyword "with" closes the connection if there is an error in my SQL?

Here my code that is executed 2000 times by another script:

try:
    engine = create_database_connection()
    with engine.connect() as connection:
        groups_sql = connection.execute(
            text('SELECT uuid, name FROM user_group WHERE project_id = :project_id'),
            project_id=project['uuid']
        ).fetchall()
except:
  print('error')
smci
  • 32,567
  • 20
  • 113
  • 146
Valentin Garreau
  • 963
  • 1
  • 10
  • 32
  • 1
    Yes that's what it's for. See [Explaining Python's '__enter__' and '__exit__'](https://stackoverflow.com/a/44387478/202229) or [What is the purpose of a context manager in python](https://stackoverflow.com/questions/36559580/what-is-the-purpose-of-a-context-manager-in-python) – smci Dec 16 '20 at 11:00
  • 1
    Moreover it will close the connection when it finishes without error too. – JeffUK Dec 16 '20 at 11:02
  • 1
    What library are you using here? We all know what a context manager is, but I do not know what does `create_database_connection` **before** the `with` block. Furthemore, opening a dabase connection per query is **very** resource consuming. – Serge Ballesta Dec 16 '20 at 11:02
  • ok thank you that answer the question – Valentin Garreau Dec 16 '20 at 11:03
  • Generally you open a database connection(s) for a session, not just an individual query. Like @SergeBallesta said. – smci Dec 17 '20 at 08:53

0 Answers0