How to Execute a SQLite Statement in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To execute a SQLite statement in Python, you can use the execute() method of a Cursor object from the sqlite3 module. Here’s an example:

import sqlite3

# Open a connection to a SQLite database
conn = sqlite3.connect('example.db')

# Create a cursor object
cursor = conn.cursor()

# Execute a SQLite statement
cursor.execute("CREATE TABLE person (name TEXT, age INTEGER)")

# Commit the changes to the database
conn.commit()

# Close the connection
conn.close()

In this example, we first establish a connection to a SQLite database file called example.db using the sqlite3.connect() method. We then create a Cursor object using the cursor() method and execute a SQLite statement to create a table called person with two columns: name of type TEXT and age of type INTEGER. We then commit the changes to the database using the commit() method and close the connection using the close() method.

Note that to execute a query or a non-query SQL statement using execute(), you need to pass in the SQL statement as a string argument. If you want to execute a SQL statement with parameters, you can use the parameter substitution syntax supported by the Python str.format() method or f-strings.

Tags:

related content