How to Connect Python with SQL Databases
Connecting Python with SQL databases is straightforward and powerful for data-driven apps, analytics, or automation. Here's a quick guide covering popular databases and how to connect to them.
✅ Common SQL Databases & Python Libraries
Database Library to Use
SQLite sqlite3 (built-in)
MySQL / MariaDB mysql-connector-python or PyMySQL
PostgreSQL psycopg2 or SQLAlchemy
Microsoft SQL Server pyodbc or pymssql
๐งฑ 1. Connect to SQLite (No Server Needed)
python
Copy code
import sqlite3
# Connect to (or create) database
conn = sqlite3.connect('example.db')
# Create a cursor
cursor = conn.cursor()
# Execute a query
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
# Commit and close
conn.commit()
conn.close()
๐ฌ 2. Connect to MySQL
bash
Copy code
pip install mysql-connector-python
python
Copy code
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdbname"
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table")
for row in cursor.fetchall():
print(row)
conn.close()
๐ 3. Connect to PostgreSQL
bash
Copy code
pip install psycopg2-binary
python
Copy code
import psycopg2
conn = psycopg2.connect(
host="localhost",
database="yourdbname",
user="yourusername",
password="yourpassword"
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
๐งฉ 4. Connect to SQL Server (MSSQL)
bash
Copy code
pip install pyodbc
python
Copy code
import pyodbc
conn = pyodbc.connect(
'DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=your_server_name;'
'DATABASE=your_database_name;'
'UID=your_username;'
'PWD=your_password'
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table")
for row in cursor.fetchall():
print(row)
conn.close()
๐ Bonus: Use SQLAlchemy (Unified Interface)
bash
Copy code
pip install sqlalchemy
python
Copy code
from sqlalchemy import create_engine
# Example: PostgreSQL
engine = create_engine('postgresql://user:password@localhost/dbname')
with engine.connect() as conn:
result = conn.execute("SELECT * FROM your_table")
for row in result:
print(row)
๐ Security Tips
Use parameterized queries to prevent SQL injection.
Avoid hardcoding credentials — use environment variables or secure vaults.
Always close connections after use.
Learn Full Stack Python Course in Hyderabad
Read More
Setting Up PostgreSQL for Full Stack Python Projects
SQL vs NoSQL: What’s Best for Full Stack Python Development?
Introduction to Databases for Full Stack Python Development
What is Full Stack Development and Why Python?
Databases and Data Storage in python
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment