Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Aaron West
256 PointsWhat is a cursor in the context of a PostgreSQL cursor (Psycopg)?
I am having trouble understanding cursors such as defined in the following code:
def connectdb(self):
self.con = psycopg2.connect(
f"host='{self.host}' "
f"user='{self.user}' "
f"password='{self.password}'")
self.cur = self.con.cursor()
I haven't really seen any documentation on this that I find easy to understand. Typically this topic just isn't broken down very well. Why would I need or want this in my code? and it seems to work fine without it.
1 Answer
Chris Freeman
Treehouse Moderator 68,468 PointsThe cursor is used to execute database commands. See Usage docs for examples. From the docs:
The main entry points of Psycopg are:
- The function
connect()creates a new database session and returns a new connection instance. - The class connection encapsulates a database session. It allows to:
- create new cursor instances using the
cursor()method to execute database commands and queries, - terminate transactions using the methods
commit()orrollback().
- create new cursor instances using the
- The class cursor allows interaction with the database:
- send commands to the database using methods such as
execute()andexecutemany(), - retrieve data from the database by iteration or using methods such as
fetchone(),fetchmany(),fetchall().
- send commands to the database using methods such as