Python SQLite cursor.execute() Function



The Python cursor.execute() function is used to form SQL commands and execute a database operation.

A Cursor is an object that is used to interact with the database. When we create a cursor, it allows us to execute SQL commands and retrieve data from the database.

If the number of parameters specified doesn't match the database, then this function throws an error.

Syntax

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

cursor.execute(sql[,optional parameters])

Parameters

This function contains SQL commands to be executed.

Return Value

The execute() function returns None.

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

This program executes a SQL query that selects the first rows form the employees table using cursor.execute() function.

cursor.execute("SELECT*FROM Employees")
x = cursor.fetchmany(1)
print(x)

Output

The result is obtained as follows −

[(1, 'Ramesh', 32, 2000.0, 'Maryland', 'USA')]

Example 2

In the below example, we are updating the salary of the employees with ID 1 to 6000.0 and retrieving the updated record using cursor.execute() function.

cursor.execute("UPDATE employees SET Salary = ? WHEREID = ?",(6000.00,1))
conn.commit()
cursor.execute("SELECT*FROM employees WHERE ID = 1)
x = cursor.fetchall()
print(x)

Output

We will get the output as follows −

[(1, 'Ramesh', 32, 6000.0, 'Maryland', 'USA')]

Example 3

Here, we are inserting a string value in place of an integer, and then this cursor.execute() function throws an exception.

cursor.execute("SELECT*FROM employees WHERE ID = ?",('one,'))

Output

The result is obtained as follows −

TypeError: integer argument expected, got stress

Example 4

Now, we are deleting the employee with ID 7 from the Employees table using the cursor.execute() function and the output confirms that the data has been deleted.

cursor.execute("DELETE FROM employees WHERE ID = ?",(7,))
conn.commit()
print("Data deleted")

Output

This produces the following result −

Data deleted
python_modules.htm