Course Content
Python Indentation, Comments and Variables
Object Oriented Programming in Python
Exception Handling in Python
Sending emails with Python
Unit test in python programming
Python programming (zero to advance!!!)
About Lesson

In Python’s SQLite module, the cursor object is used to execute SQL queries and fetch data from the database. It acts as a pointer to a specific location in the result set of a query, allowing you to iterate over the rows returned by the query and perform various operations on them.

Here’s how you can work with the cursor object in SQLite:

1. Creating a Cursor: To create a cursor object, you first need to establish a connection to the SQLite database using the `connect()` method, and then call the `cursor()` method on the connection object.

2. Executing Queries: Once you have a cursor object, you can use it to execute SQL queries using the `execute()` method. This method takes an SQL query as its argument and executes it against the database.

3. Fetching Data: After executing a query, you can fetch the results using methods like `fetchone()`, `fetchall()`, or `fetchmany()`. These methods allow you to retrieve one row, all rows, or a specified number of rows from the result set, respectively.

4. Iterating Over Results: You can iterate over the rows returned by a query using a `for` loop or a list comprehension. Each row fetched from the cursor represents a tuple of values corresponding to the columns in the result set.

5. Closing the Cursor: Once you’re done working with the cursor, it’s good practice to close it using the `close()` method. This releases any resources associated with the cursor and frees up memory.

Here’s a basic example demonstrating how to use the cursor object in SQLite:

import sqlite3

# Connect to the SQLite database
connection = sqlite3.connect(‘example.db’)

# Create a cursor object
cursor = connection.cursor()

# Execute a SQL query
cursor.execute(“SELECT * FROM example”)

# Fetch one row from the result set
row = cursor.fetchone()

# Fetch all rows from the result set
rows = cursor.fetchall()
for row in rows:

# Close the cursor and connection

In this example:

– We establish a connection to an SQLite database file named `example.db`.
– We create a cursor object using the `cursor()` method.
– We execute a SELECT query to retrieve all rows from the `example` table.
– We fetch one row using the `fetchone()` method and print it.
– We fetch all remaining rows using the `fetchall()` method and iterate over them, printing each row.
– Finally, we close the cursor and connection.

Join the conversation