Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python SQLite connection.cursor() Function



The Python connection.cursor() function creates a cursor object, which is essential for executing SQL commands and retrieving data from the database.

A cursor acts as a control structure that allows navigating over the records in the database. This function is used to connect all the commands in the database through the cursor.

By using the cursor, we are executing SQL queries, retrieving results, and managing commands. After completing the database operations, it is very important to close the cursor.

Syntax

Following is the basic syntax for the connection.cursor() function.

connection.cursor([cursorClass])

Parameters

This cursorclass is used to create a cursor object, if the cursor is not provided, then the default cursor will be used.

Return Value

This function returns a cursor object.

Example 1

This program connects to an SQLite database, executes a query to get the SQL version, and closes the connection using connection.cursor() function.

import sqlite3
conn = sqlite3.connect('res.db')
cursor = conn.cursor()
cursor.execute('SELECT sqlite_version()')
version = cursor.fetchone()
print(f'SQLite version:{version[0]}')
cursor.close()
conn.close()

Output

When we run the above code, we will get the following output −

SQLite version: 3.39.2

Example 2

This example connects to an SQLite database. Here we are going to create a table, insert the values and then close the connection using connection.cursor() function.

import sqlite3
conn = sqlite3.connect('res.db')
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
cursor.execute("INSERT INTO users(name,age)VALUES(x,y)",('Markas',20))
cursor.execute("INSERT INTO users(name,age)VALUES(x,y)",('Tillu',45))
conn.commit()
cursor.close()
conn.close()

Output

The result is produced as follows −

(1, 'Markas', 20)
(2, 'Tillu', 45)

Example 3

When the cursor takes no arguments from the database, this function throws a TypeError.

import sqlite3
conn = sqlite3.connect('res.db')
try:
   cursor = con.cursor('invalid_argument')
except TypeError as e:
   print(f'TypeError: {e}')
conn.close()

Output

We will get the output as follows −

TypeError: cursor() takes no arguments
python_modules.htm
Advertisements