Junior
210
What is a cursor in the context of working with databases and what is its function?
Answer from AI
sobes.tech AI
A cursor is an object used to iterate over the rows of a query result set from a database.
Its functions:
- Row-by-row data access: Allows processing data from the result set one row at a time, rather than loading the entire set into memory.
- Current position management: Tracks which row in the result set is currently being processed.
- Operations on the current row: Enables operations such as update or delete on the specific row pointed to by the cursor.
In Python, when working with database access libraries (e.g., psycopg2 for PostgreSQL or sqlite3 for SQLite), cursors are created from connection objects:
# Python
import sqlite3
conn = sqlite3.connect(':memory:')
cursor = conn.cursor() # Creating a cursor object
cursor.execute("SELECT 1")
row = cursor.fetchone() # Fetching one row from the result set
cursor.close() # Closing the cursor
conn.close() # Closing the connection