Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Executing SQL queries with Python

Learn how to execute SQL queries, insert data into a database, and retrieve results using Python. …


Updated June 26, 2023

Learn how to execute SQL queries, insert data into a database, and retrieve results using Python. Executing SQL Queries


Definition of the Concept

Executing SQL (Structured Query Language) queries is an essential part of working with databases. It allows you to interact with a database by sending SQL commands to perform various operations such as inserting, updating, deleting, or retrieving data.

SQL queries are used to manage and manipulate data in relational databases like MySQL, PostgreSQL, SQLite, etc. Python provides several libraries that enable you to execute SQL queries and work with databases.

Step-by-Step Explanation

Step 1: Install a Database Library

To work with databases in Python, you need to install a library that can connect to your database management system (DBMS). Some popular choices are:

  • sqlite3 for SQLite databases
  • mysql-connector-python for MySQL databases
  • psycopg2 for PostgreSQL databases

You can install these libraries using pip:

pip install sqlite3
# or
pip install mysql-connector-python
# or
pip install psycopg2-binary

Step 2: Connect to the Database

Once you have installed the library, import it in your Python script and establish a connection to the database.

import sqlite3

# for SQLite databases
conn = sqlite3.connect('example.db')

# for MySQL or PostgreSQL databases
import mysql.connector
cnx = mysql.connector.connect(
    user='username',
    password='password',
    host='localhost',
    database='database_name'
)

Step 3: Execute a SQL Query

You can execute a SQL query using the cursor.execute() method. Here’s an example:

cur = conn.cursor()
cur.execute("SELECT * FROM users")
rows = cur.fetchall()
for row in rows:
    print(row)
conn.close()

This code executes a SELECT query on the users table and prints each row.

Step 4: Insert Data into the Database

To insert data into the database, use the INSERT INTO SQL statement.

cur = conn.cursor()
cur.execute("INSERT INTO users (name, age) VALUES ('John Doe', 30)")
conn.commit()

This code inserts a new record into the users table with the name “John Doe” and age 30.

Step 5: Close the Database Connection

Remember to close the database connection when you’re done.

conn.close()

Code Explanation

Here’s an explanation of each part of the code:

  • import sqlite3: This line imports the SQLite library, allowing us to work with SQLite databases.
  • conn = sqlite3.connect('example.db'): This line establishes a connection to an SQLite database named “example.db”.
  • cur = conn.cursor(): This line creates a cursor object that we can use to execute SQL queries.
  • cur.execute("SELECT * FROM users"): This line executes a SELECT query on the users table and stores the result in the rows variable.
  • rows = cur.fetchall(): This line fetches all rows from the query result.
  • for row in rows: print(row): This loop iterates over each row in the result and prints it.

Best Practices

Here are some best practices to keep in mind when working with databases in Python:

  • Always close the database connection when you’re done.
  • Use parameterized queries to prevent SQL injection attacks.
  • Handle exceptions properly to ensure that your code is robust and reliable.

By following these guidelines, you can write efficient and effective code that works seamlessly with databases.

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp