Python SQLite cursor.executescript() Function
A Python cursor.executescript() function is used for executing multiple SQL commands at once. This takes a single string containing multiple SQL commands separated by semicolons. This function is useful for creating databases and performing multiple operations on a single set.
A cursor is an object that is used to execute SQL commands and retrieve data. When we create a cursor from the database connection, this retrieves SQL queries and results from the database.
Syntax
Following is the syntax for the cursor.executescript() function.
cursor.executescript(sql_script)
Parameters
Multiple SQL commands on a single string are separated by semicolons.
Return Value
This function is used to execute multiple SQL commands, and it 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
The below example selects all the names and cities of employees who are from India using cursor.executescript() function.
sql_script = ''' SELECT Name, City FROM employees WHERE country = 'India';''' cursor.executescriot(sql_script)
Output
When we run the above code, we will get the following result −
Kaushik Kolkata Hardik Bhopal Komal Saharanpur Ayush Delhi
Example 2
In the below example, we are calculating the average salary of the employees using cursor.executescript() function.
sql_script = ''' SeleCT AVG(Salary) AS Average_Salary FROM employees;''' cursor.executescript(sql_script)
Output
The result is obtained as follows −
Average_Salary 3500.00
Example 3
We are now updating the salaries of employees whose salaries are now greater than 4000 using cursor.executescript() function.
sql_script = ''' UPDATE employees = SAlary *1.1 WHERE Country = 'India'; SELECT NAME, Salary FROM employees WHERE Salary > 4000;''' cursor.executescript(sql_script)
Output
The result is produced as follows −
Mukesh 5000.00 Sumit 4500.00 Komal 3850.00
Example 4
In the below example, we are updating the statements by multiplying the salary by a string, which is not a valid operation. This function throws a TypeError because an integer value cannot be multiplied by a string.
sql_script = ''' UPDATE employees SET Salary = Salary * 'five' WHERE Salary > 5000;
SELECT Name, Salary FROM employees WHERE Salary > 4000;'''
try:
cursor.executescript(sql_script)
except TypeError as e:
print(f"TypeError: {e}")
Output
The result is produced as follows −
TypeError: can't multiply sequence by non-int of type 'str'
python_modules.htm