Manu mathew
Manu mathew

Reputation: 989

Will connection.cursor() as cursor create new connection?

If am doing the following in Django, will a new connection object be created for every query execution?

for query in query_list:
    with connection.cursor() as cursor:
        cursor.execute(query)

Upvotes: 4

Views: 8628

Answers (1)

Learning is a mess
Learning is a mess

Reputation: 8277

with connection.cursor() as cursor:
    cursor.execute(query)

with keyword means you are using a context manager in Python, at the end of this block connection.__exit__ is silently called and the connection is closed. Likewise at the beginning of the block connection.__enter__ is executed.

To answer your question, yes you are opening and closing a connection for each query in query_list. If you want to avoid that permute the loop and the context manger, as:

with connection.cursor() as cursor:
    for query in query_list:
        cursor.execute(query)

Upvotes: 8

Related Questions