Python sqlite3: execute(), executescript(), and executemany() – Examples

Updated: February 6, 2024 By: Guest Contributor Post a comment

Introduction

The sqlite3 module is a part of Python’s standard library, making it an accessible option for working with SQLite databases. SQLite is a C-library that provides a lightweight disk-based database. It does not require a separate server process, which makes it a perfect choice for small to medium-sized applications, testing environments, or even production applications when used correctly.

In this tutorial, we’ll dive into the sqlite3 module in Python, focusing on three critical methods for interacting with SQLite databases: execute(), executescript(), and executemany(). Whether you’re a beginner or have some experience with databases, understanding these methods is key to performing database operations efficiently. We’ll start with the basics and gradually explore more advanced examples, complete with outputs to guide your learning.

Using execute() Method

The execute() method is used to execute a single SQL command. This is the most basic way to interact with a database and is commonly used for operations such as creating tables, inserting data, and querying data.

# Example 1: Creating a table using execute()
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE students (id integer primary key, name text, grade text)''')
conn.commit()
conn.close()

This example showcases the creation of a table named students. By committing the changes with conn.commit() and then closing the connection with conn.close(), we ensure that our database is updated successfully.

Inserting Data

# Example 2: Inserting data using execute()
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("INSERT INTO students (name, grade) VALUES ('John Doe', 'A')")
conn.commit()
conn.close()

Once a table is created, inserting data into it through the execute() method is straightforward. Remember to commit your changes and close the connection to reflect the data in your database.

Querying Data

# Example 3: Querying data using execute()
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('SELECT * FROM students')
results = c.fetchall()
print(results)
conn.close()

Querying data involves executing a SELECT statement and then calling fetchall() to retrieve the results, which are returned as a list of tuples.

The executescript() Method

The executescript() method takes a string containing one or more SQL scripts that are executed sequentially. It’s particularly useful for executing a batch of SQL commands at once.

# Example 4: Using executescript()
conn = sqlite3.connect('example.db')
c = conn.cursor()
script = '''
    DROP TABLE IF EXISTS students;
    CREATE TABLE students (id integer primary key, name text, grade text);
    INSERT INTO students (name, grade) VALUES ('Jane Doe', 'B');
'''
c.executescript(script)
conn.commit()
conn.close()

This example demonstrates how we can use executescript() to execute multiple SQL statements, streamlining the process of setting up a database schema and seeding it with initial data.

Using executemany() Method

The executemany() method is designed for executing a SQL command against a sequence of parameters. This is extremely useful for bulk-inserting data.

# Example 5: Bulk-inserting data using executemany()
conn = sqlite3.connect('example.db')
c = conn.cursor()
data = [('Mike Wazowski', 'A'), ('Sullivan', 'B')]
c.executemany('INSERT INTO students (name, grade) VALUES (?, ?)', data)
conn.commit()
conn.close()

By preparing a list of tuples each corresponding to a row of data, we can insert multiple entries into our database efficiently using the executemany() method.

Conclusion

The sqlite3 module’s execute(), executescript(), and executemany() methods provide powerful tools for interacting with SQLite databases in Python. By mastering these methods, you can greatly simplify database operations, from setting up schemas to inserting and querying data. Experimenting with these examples will help solidify your understanding and improve your database management skills.