Course contentsShow
← Data Science
Lesson 1094 of 2,14528. Working with Databases from PythonFree lesson

Cursor Objects and Query Execution

Learn to create cursor objects and execute SQL queries using Python's database API specification.

Cursor Objects and Query Execution

What You'll Learn

You'll learn how to create cursor objects and use them to execute SQL queries through Python's database connection.

The Core Idea

Once you've established a database connection, you don't execute queries directly on that connection object. Instead, you create a cursor — think of it as a control structure that manages query execution and fetches results. The cursor acts like a pointer that moves through your query results row by row.

After creating a cursor from your connection, you use it to send SQL commands to the database and retrieve data back into Python.

How Cursors Work

Creating a Cursor

From your established connection (whether sqlite3 or psycopg2), call the .cursor() method:

import sqlite3

conn = sqlite3.connect('example.db')
cursor = conn.cursor()

Executing Queries

Use the cursor's .execute() method to run SQL commands:

# Execute a SELECT query
cursor.execute("SELECT * FROM customers WHERE country = 'USA'")

# Execute an INSERT
cursor.execute("INSERT INTO products (name, price) VALUES ('Widget', 9.99)")

The cursor handles sending your SQL to the database engine and preparing to receive results.

The Analogy

Think of the connection as your phone line to the database, and the cursor as the conversation you're having. You can have multiple conversations (cursors) over one phone line (connection), each tracking its own place in the dialogue.

Why Cursors Matter

Cursors separate connection management from query execution. This design lets you run multiple queries through different cursors on the same connection, manage result sets independently, and follow a consistent API across different database systems.

Key Takeaway: Cursors are your interface for executing SQL queries and retrieving results — create them from connections using .cursor() and run queries with .execute()