The Wayback Machine - https://web.archive.org/web/20241107164836/https://www.geeksforgeeks.org/how-to-execute-many-sqlite-statements-in-python/
Open In App

How to Execute many SQLite Statements in Python?

Last Updated : 30 Jun, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In SQLite using the executescript() method, we can execute multiple SQL statements/queries at once. The basic execute() method allows us to only accept one query at a time, so when you need to execute several queries we need to arrange them like a script and pass that script to the executescript() method.

executescript() can be able to execute series of several SQL/SQLite queries in a row. While executescript() operation is running, the other threads/operations are not able to access the database until executescript() has finished executing all its queries. In case we need to provide some runtime parameter for each of the queries in executescript() we cannot add an external parameter at runtime as executescript() method doesn’t accept any parameter for the query in runtime so you need to give a set of static queries as a script. In the execution of executescript() method, first, it issues a COMMIT statement and then executes the SQL/SQLite script.

Syntax:

cursor_obj.executescript(""" 
    SQLite Statement/Query . . . 1
    SQLite Statement/Query . . . 2
    SQLite Statement/Query . . . 3
    .
    .
    .
    SQLite Statement/Query . . . n 
""")

The below code shows how to execute multiple SQLite statements/queries in python:

Python3




import sqlite3 
  
  
# make the database connection and cursor object
connection = sqlite3.connect("CollegeData.db")
cursor = connection.cursor()
  
# create a set of queries in executescript()
# below set of queries will create and insert
# data into table
cursor.executescript(""" 
    CREATE TABLE department( deptId INTEGER,
    deptName VARCHAR(20), deptScore INTEGER); 
  
    INSERT INTO department VALUES ( 01,'IT', 850 );
    INSERT INTO department VALUES ( 02,'COMP', 840 );
    INSERT INTO department VALUES ( 03,'CIVIL', 500 );
    INSERT INTO department VALUES ( 04,'E&TC;', 650 );
""")
  
# fetch the table data
print("Table data :")
cursor.execute("SELECT * FROM department") 
print(cursor.fetchall())
  
# below set of queries will update the data
# of in the table
cursor.executescript("""
    UPDATE department set deptScore = 900 where deptId = 01;
    UPDATE department set deptScore = 890 where deptId = 02;
    UPDATE department set deptScore = 660 where deptId = 03;
    UPDATE department set deptScore = 790 where deptId = 04;
""")
  
# fetch the table data after updation
print("Table data after updation :")
cursor.execute("SELECT * FROM department") 
print(cursor.fetchall())
  
# commit the changes and close the database
# connection 
connection.commit() 
connection.close()


Output

Table data :

[(1, ‘IT’, 850), (2, ‘COMP’, 840), (3, ‘CIVIL’, 500), (4, ‘E&TC’, 650)]

Table data after updation :

[(1, ‘IT’, 900), (2, ‘COMP’, 890), (3, ‘CIVIL’, 660), (4, ‘E&TC’, 790)]

The above code executes multiple SQLite statements at once. The first executescript() method in the code creates and inserts the data into a table in one instance. And then second executescript() method updates all the records in one instance. In this way, a set of many queries can be executed in SQLite using executescript().



Previous Article
Next Article

Similar Reads

How to Execute a Script in SQLite using Python?
In this article, we are going to see how to execute a script in SQLite using Python. Here we are executing create table and insert records into table scripts through Python. In Python, the sqlite3 module supports SQLite database for storing the data in the database. Approach Step 1: First we need to import the sqlite3 module in Python. import sqlit
2 min read
How to Execute a SQLite Statement in Python?
In this article, we are going to see how to execute SQLite statements using Python. We are going to execute how to create a table in a database, insert records and display data present in the table. In order to execute an SQLite script in python, we will use the execute() method with connect() object: connection_object.execute("sql statement") Appr
2 min read
Python If Else Statements - Conditional Statements
In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code. Conditional statements in Python play a key role in determin
8 min read
How to Show a Many-to-Many Field with "list_display" in Django Admin
In Django, the list_display attribute in the Django Admin interface allows developers to specify which fields to display in the list view of the admin panel. This feature is particularly useful for providing a quick overview of the model instances. However, displaying many-to-many fields in the list_display can be a bit tricky since these fields ca
3 min read
CRUD Operation On A Django Model With A Many-to-Many Field
Django provides a powerful and flexible way to work with relational databases through its Object-Relational Mapping (ORM). One of the common relationships we encounter in database design is the Many-to-Many relationship. In Django, this relationship is represented using a ManyToManyField. In this article, we'll explore how to create, read, update,
4 min read
Python | Execute and parse Linux commands
Prerequisite: Introduction to Linux Shell and Shell Scripting Linux is one of the most popular operating systems and is a common choice for developers. It is popular because it is open source, it's free and customizable, it is very robust and adaptable. An operating system mainly consists of two parts: The kernel and the Shell. The kernel basically
6 min read
How to Execute Shell Commands in a Remote Machine in Python?
Running shell commands on a Remote machine is nothing but executing shell commands on another machine and as another user across a computer network. There will be a master machine from which command can be sent and one or more slave machines that execute the received commands. Getting Started We will be using Websocket protocol to send shell comman
3 min read
How to Execute Shell Commands in a Remote Machine using Python - Paramiko
Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement for SSL to make a secure connection between two devices. It also supports the SFTP client and server model. Authenticating SSH connection To authenticate an SSH connection, we need to set up a private RSA SSH key (not to be
4 min read
Execute PostgreSQL Stored Procedure and Function in Python
A stored procedure is a sequence of structured procedural language queries stored in a relational database management system as a data dictionary, which can be shared and reused multiple times. All CRUD operations, querying operations can be performed by calling the stored procedure. The use of stored procedures reduces the repetition of code that
3 min read
Execute a String of Code in Python
Given few lines of code inside a string variable and execute the code inside the string. Examples: Input: code = """ a = 6+5 print(a)""" Output: 11 Explanation: Mind it that "code" is a variable and not python code. It contains another code, which we need to execute. Input: code = """ def factorial(num): for i in range(1,num+1): fact = fact*i retur
3 min read
How to Execute a Python Script from the Django Shell?
The Django shell is an interactive development and scripting environment that aids us in working with our Django project while experiencing it as if it were deployed already. It is most commonly used when one has to debug, test, or carry out one-time operations that require interaction with the Django models. However, such incidents can arise that
4 min read
PyQt5 QColorDialog - How to execute it ?
In this article we will see how we can execute the QColorDialog widget, executing means to opening it. There are basically two ways of opening the QColorDialog one is to call the getColor method, this is a static way that will open the new instance of QColorDialog every time, this way is useful for quick uses but not preferred. The second way is by
2 min read
How to execute raw SQL in Flask-SQLAlchemy app
In this article, we are going to see how to execute raw SQL in Flask-SQLAlchemy using Python. Installing requirements Install the Flask and Flask-SQLAlchemy libraries using pip pip install Flask pip install flask_sqlalchemySyntaxTo run raw SQL queries, we first create a flask-SQLAlchemy engine object using which we can connect to the database and e
4 min read
How to Execute Raw SQL in SQLAlchemy
In this article, we will see how to write a Conventional SQL query in SQLAlchemy using text() against a PostgreSQL database in python. Creating table for demonstration Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books w
3 min read
Execute a Subset of Test Suite in Pytest
A testing framework in Python that is used to write API test cases is called Pytest. There are some circumstances in which the user doesn't want to execute all the test suites, but want to execute only certain test cases. In such instances, you can run test suites based on substring matching of test names or on the markers applied. Execute a Subset
3 min read
Periodically Execute a Function with asyncio in Tornado
The primary benefit is improved performance. Asynchronous programming allows your application to efficiently handle tasks that may block the main thread, such as network operations or I/O-bound tasks. This can lead to better responsiveness and scalability. Also by controlling the frequency of periodic tasks in Tornado, you can control the frequency
4 min read
How to Execute SQL queries from CGI scripts
In this article, we will explore the process of executing SQL queries from CGI scripts. To achieve this, we have developed a CGI script that involves importing the database we created. The focus of this discussion will be on writing code to execute SQL queries in Python CGI scripts. The initial step involves creating a database, and it's worth noti
5 min read
Loops and Control Statements (continue, break and pass) in Python
Python programming language provides the following types of loops to handle looping requirements. Python While Loop Until a specified criterion is true, a block of statements will be continuously executed in a Python while loop. And the line in the program that follows the loop is run when the condition changes to false. Syntax of Python Whilewhile
4 min read
Difference between continue and pass statements in Python
Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from its normal sequence. When execution leaves a scop
3 min read
Python - Multi-Line Statements
In this article, we are going to understand the concept of Multi-Line statements in the Python programming language. Statements in Python: In Python, a statement is a logical command that a Python interpreter can read and carry out. It might be an assignment statement or an expression in Python. Multi-line Statement in Python: In Python, the statem
3 min read
Jump Statements in Python
In any programming language, a command written by the programmer for the computer to act is known as a statement. In simple words, a statement can be thought of as an instruction that programmers give to the computer and upon receiving them, the computer acts accordingly. There are various types of statements in programming and one such type of sta
4 min read
Alternatives to Case/Switch Statements in Python
In many programming languages, the case or switch statement is a control flow mechanism that allows a variable to be tested for equality against a list of values, with each value associated with a block of code to be executed. However, Python does not have a built-in case or switch statement. Instead, Python developers use various alternative struc
3 min read
Conditional Statements in Python
Understanding and mastering Python's conditional statements is fundamental for any programmer aspiring to write efficient and robust code. In this guide, we'll delve into the intricacies of conditional statements in Python, covering the basics, advanced techniques, and best practices. What are Conditional Statements?Conditional Statements are state
6 min read
Python SQLite - Insert Data
In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows: Only values: The first method is to specify only the value of data to b
3 min read
SQL using Python and SQLite | Set 2
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web, and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to S
3 min read
Python SQLite - Update Data
In this article, we will discuss how we can update data in tables in the SQLite database using Python - sqlite3 module. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. Syntax: UPDATE table_name SET col
7 min read
How to Create a Backup of a SQLite Database using Python?
In this article, we will learn How to Create a Backup of an SQLite Database using Python. To Create a Backup of an SQLite Database using Python, the required modules are SQLite3 and IO. First, let's create the original database to do that follow the below program: C/C++ Code import sqlite3 import io from sqlite3 import Error def SQLite_connection()
2 min read
Introduction to SQLite in Python
Databases offer numerous functionalities by which one can manage large amounts of information easily over the web and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases. Many websites use MySQL. SQLite is a "light" version that works over syntax very much similar to SQ
3 min read
Python SQLite - Update Specific Column
In this article, we will discuss how to update a specific column of a table in SQLite using Python. In order to update a particular column in a table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE stat
3 min read
How to store Python functions in a Sqlite table?
SQLite is a relational database system contained in a C library that works over syntax very much similar to SQL. It can be fused with Python with the help of the sqlite3 module. The Python Standard Library sqlite3 was developed by Gerhard Häring. It delivers an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. To use t
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg