Python MySQL SELECT
Query: Fetching Data from Your Database
Working with databases is a crucial part of web development. Whether you’re building a blog, e-commerce site, or a learning platform, fetching data efficiently is essential. In this post, we'll explore how to use Python to perform a SELECT
query on a MySQL database using the mysql-connector-python
library.
Prerequisites
Before we get started, make sure:
- You have MySQL installed and running.
- Python is installed on your system.
- You’ve installed the MySQL connector:
pip install mysql-connector-python
Step 1: Connect to MySQL Database
First, import the required library and establish a connection:
import mysql.connector
# Connect to your MySQL database
conn = mysql.connector.connect(
host="localhost", # or your DB host
user="yourusername", # your DB username
password="yourpassword",
database="yourdatabase"
)
cursor = conn.cursor()
Step 2: Write and Execute the SELECT
Query
Let’s assume you have a table called blogs
. To fetch all blog posts, you can run:
query = "SELECT * FROM blogs"
cursor.execute(query)
You can also fetch only specific columns:
query = "SELECT title, author FROM blogs"
cursor.execute(query)
Step 3: Fetch the Results
Use one of the following methods:
fetchall()
– to get all rowsfetchone()
– to get a single row
Example:
results = cursor.fetchall()
for row in results:
print("Title:", row[0], "| Author:", row[1])
Sample Output:
Title: Learn Python | Author: Admin
Title: MySQL Basics | Author: John
Step 4: Close the Connection
Don’t forget to close the cursor and connection:
cursor.close()
conn.close()
Final Notes
- Always sanitize input to prevent SQL injection.
- For dynamic queries, use parameterized queries with placeholders (
%s
).
Example:
query = "SELECT * FROM blogs WHERE author = %s"
cursor.execute(query, ("John",))
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.