Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

485
Views
What is the advantage of using multiple cursors in psycopg2 for PostgreSQL queries?

What is the difference between using a single cursor in psycopg2 to perform all your queries against using multiple cursors.

I.e, say I do this:

import psycopg2 as pg2
con = psycopg2.connect(...)
cur = con.cursor()
cur.execute(...)
....
....
cur.execute(...)
...

and every time I wish to execute a query thereafter, I use the same cursor cur.

Alternatively I could do this every time I want to query my database:

with cur as con.cursor():
    cur.execute(...)

In which case, my cursor cur would be deleted after every use.

Which method is better? Does one have an advantage over another? Is one faster than the other? More generally, why are multiple cursors for one connection even needed?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The two options are comparable; you can always benchmark both to see if there's a meaningful difference, but psycopg2 cursors are pretty lightweight (they don't represent an actual server-side, DECLAREd cursor, unless you pass a name argument) and I wouldn't expect any substantial slowdown from either route.

The reason psycopg2 has cursors at all is twofold. The first is to be able to represent server-side cursors for situations where the result set is larger than memory, and can't be retrieved from the DB all at once; in this case the cursor serves as the client-side interface for interacting with the server-side cursor.

The second is that psycopg2 cursors are not thread-safe; a connection object can be freely used by any thread, but each cursor should be used by at most one thread. Having a cursor-per-thread allows for multithreaded applications to access the DB from any thread, while sharing the same connection.

See the psycopg2 usage docs on server side cursors and thread and process safety for more details.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!