Python Execute SQL Query
Python Execute SQL Query
Let’s learn how to execute an SQL query on an SQLite database in Python. We can use the sqlite3 module’s DB APIs to execute SQL queries on an SQLite database.
Details on how to create an SQLite cursor object are listed here.
Execute SQL Query
The sqlite3 module supports two kinds of ways to execute the SQL query in Python
programs.
- Using the connection object execute() method
- Using the cursor object execute() method
cursor.execute(SQL Query)
The above call executes the SQL statement. The SQL statement may be parameterized
using placeholders instead of SQL literals. The function supports two kinds of placeholders:
- Question marks
- Named placeholders
connection.execute(sql)
This function creates an intermediate cursor object by calling the cursor method and then calls the cursor’s execute() method.
Use methods like fetchone(), fetchall(), or fetchmany() to retrieve data from the database.
Example
# Python program to Execute SQL Query
# Python Tutorials – www.TestingDocs.com
import sqlite3
# Open SQLite DB Connection
connection = sqlite3.connect(“tdocs_database.db”)
cursor = connection.cursor()
# Execute SQL Query
cursor.execute(‘SELECT * FROM employees’)
rows = cursor.fetchall()
for row in rows:
print(row)
connection.commit()
connection.close()
Program Output
Run the program. The program will output the rows in the table. We can verify the table data using the DB Browser for SQLite.
—
Python Tutorials
Python Tutorial on this website can be found at:
https://www.testingdocs.com/python-tutorials/
More information on Python is available at the official website: