Python SQLite cursor.fetchone() Function



The Python cursor.fetchone() function retrieves data from the next query, this function returns a single sequence or None when there is no data is available.

This function can be used as an iterator, and this fetechone() can also be called fetchall() and fetchmany(). It is particularly useful when we expect a query to return a single row or when we want to process rows one at a time.

Syntax

Following is the syntax for the cursor.fetchone() function.

row = cursor.fetchone()

Parameters

This function doesn't take any parameters.

Return Value

If a single row is available, then this function returns the next row as a tuple.

Example

Consider the following EMPLOYEES table which stores employees ID, Name, Age, Salary, City and Country −

IDNameAgeSalaryCityCountry
1Ramesh322000.00MarylandUSA
2Mukesh405000.00New YorkUSA
3Sumit454500.00MuscatOman
4Kaushik252500.00KolkataIndia
5Hardik293500.00BhopalIndia
6Komal383500.00SaharanpurIndia
7Ayush253500.00DelhiIndia

Example 1

Here's an example using the cursor.fetchone() function to retrieve the first row from the table.

import sqlite3
conn = sqlite3.connect('res.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM employees")
row = cursor.fetchone()
print(row)

Output

We will get the result as follows −

IDNameAgeSalaryCityCountry
1Ramesh322000.00MarylandUSA

Example 2

In the example below, we are going to delete the first row from the table using the cursor.fetchone(), then this function will return the second row from the database.

import sqlite3
conn = sqlite3.connect('res.db')
cursor = conn.cursor()
cursor.execute("DELETE FROM employees WHERE ID = 1")
conn.commit()
cursor.execute("SELECT  * FROM employees")
print(cursor.fetchone())
conn.close()

Output

The result is obtained as follows −

IDNameAgeSalaryCityCountry
2Mukesh405000.00New YorkUSA

Example 3

Now, we are updating the first row in the database. Using the cursor.fetchone() function, it will then return the updated first row from the database.

import sqlite3
conn = sqlite3.connect('res.db')
cursor = conn.cursor()
cursor.execute("UPDATE employees SET Salary = 5500.00 WHERE ID = 1")
cursor.commit()
cursor.execute("SELECT * FROM employees WHERE ID = 1")
print(cursor.fetechone())
conn.close()

Output

The output is obtained as follows −

IDNameAgeSalaryCityCountry
1Ramesh325500.00MarylandUSA
python_modules.htm