Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python SQLite – Cursor Object

  • Last Updated : 09 May, 2021

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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
         (FID 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 FID,FNAME from hotel ")
  
# display all data from FOOD1 table
for row in cursor:
     print(row)

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!