Python SQLite – Cursor Object
Last Updated :
16 Feb, 2022
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
import sqlite3
connection = sqlite3.connect( 'hotel_data.db' )
connection.execute(
)
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" )
cursor = connection.execute( "SELECT * from hotel " )
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
import sqlite3
connection = sqlite3.connect( 'hotel_data.db' )
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" )
cursor = connection.execute( "SELECT FIND,FNAME from hotel " )
for row in cursor:
print (row)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...