After executing the SQL statement for reading records from a table, either of the following methods can be used to retrieve them in python.
fetchone: It retrieves one record at a time in the form of a tuple.
fetchall: It retrieves all fetched records at a point in the form of tuple of tuples.
Fetching Sample Data
Example 1
import sqlite3
# establishing the connection
con = sqlite3.connect('D:\\TEST.db')
# preparing a cursor object
cursor = con.cursor()
# preparing sql statement
sql = '''
SELECT * FROM EMPLOYEE
'''
# executing the sql statement using `try ... except`
try:
cursor.execute(sql)
except:
print('Unable to fetch data.')
# fetching the records
records = cursor.fetchall()
# Displaying the records
for record in records:
print(recoriv)
# closing the connection
con.close()
The above example fetches and displays all five records inserted into EMPLOYEE.