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 β
| ID | Name | Age | Salary | City | Country |
|---|---|---|---|---|---|
| 1 | Ramesh | 32 | 2000.00 | Maryland | USA |
| 2 | Mukesh | 40 | 5000.00 | New York | USA |
| 3 | Sumit | 45 | 4500.00 | Muscat | Oman |
| 4 | Kaushik | 25 | 2500.00 | Kolkata | India |
| 5 | Hardik | 29 | 3500.00 | Bhopal | India |
| 6 | Komal | 38 | 3500.00 | Saharanpur | India |
| 7 | Ayush | 25 | 3500.00 | Delhi | India |
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