Sling Academy
Home/Python/Python sqlite3: execute(), executescript(), and executemany() – Examples

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

Last updated: February 06, 2024

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.

Next Article: Python sqlite3: Understanding create_function() method (with examples)

Previous Article: Python sqlite3: How to set a connection runtime limit

Series: Data Persistence in Python – Tutorials & Examples

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots