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 moduleimport sqlite3# create connection by using object# to connect with hotel_data databaseconnection = sqlite3.connect('hotel_data.db')# query to create a table named FOOD1connection.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 tableconnection.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 querycursor = connection.execute("SELECT * from hotel ")# display all data from hotel tablefor 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 moduleimport sqlite3# create connection by using object# to connect with hotel_data databaseconnection = sqlite3.connect('hotel_data.db')# insert query to insert food details# in the above tableconnection.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 querycursor = connection.execute("SELECT FIND,FNAME from hotel ")# display all data from FOOD1 tablefor row in cursor: print(row) |
Output:




