Saturday, September 27, 2025
HomeLanguagesPython SQLite – Cursor Object

Python SQLite – Cursor Object

In this article, we are going to discuss cursor objects in sqlite3 module of Python.

Cursor Object

It is an object that is used to make the connection for executing SQL queries. It acts as middleware between SQLite database connection and SQL query. It is created after giving connection to SQLite database.

Syntax: cursor_object=connection_object.execute(“sql query”);

Example 1: Python code to create a hotel_data database and insert records into the hotel table.

Python3




# importing sqlite3 module
import sqlite3
 
 
# create connection by using object
# to connect with hotel_data database
connection = sqlite3.connect('hotel_data.db')
 
# query to create a table named FOOD1
connection.execute(''' CREATE TABLE hotel
         (FIND INT PRIMARY KEY     NOT NULL,
         FNAME           TEXT    NOT NULL,
         COST            INT     NOT NULL,
         WEIGHT        INT);
         ''')
 
# insert query to insert food  details in
# the above table
connection.execute("INSERT INTO hotel VALUES (1, 'cakes',800,10 )")
connection.execute("INSERT INTO hotel VALUES (2, 'biscuits',100,20 )")
connection.execute("INSERT INTO hotel VALUES (3, 'chocos',1000,30 )")
 
 
print("All data in food table\n")
 
# create a cousor object for select query
cursor = connection.execute("SELECT * from hotel ")
 
# display all data from hotel table
for row in cursor:
    print(row)


Output:

Now go to your location and see the SQLite database is created.

Example 2: Python code to display data from hotel table.

Python3




# importing sqlite3 module
import sqlite3
 
# create connection by using object
# to connect with hotel_data database
connection = sqlite3.connect('hotel_data.db')
 
 
# insert query to insert food  details
# in the above table
connection.execute("INSERT INTO hotel VALUES (1, 'cakes',800,10 )");
connection.execute("INSERT INTO hotel VALUES (2, 'biscuits',100,20 )");
connection.execute("INSERT INTO hotel VALUES (3, 'chocos',1000,30 )");
 
 
print("Food id and Food Name\n")
 
# create a cousor object for select query
cursor = connection.execute("SELECT FIND,FNAME from hotel ")
 
# display all data from FOOD1 table
for row in cursor:
     print(row)


Output:

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32322 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6690 POSTS0 COMMENTS
Nicole Veronica
11857 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11913 POSTS0 COMMENTS
Shaida Kate Naidoo
6804 POSTS0 COMMENTS
Ted Musemwa
7073 POSTS0 COMMENTS
Thapelo Manthata
6763 POSTS0 COMMENTS
Umr Jansen
6768 POSTS0 COMMENTS