SQL Tutorial
SQL Clauses / Operators
SQL-Injection
SQL Functions
SQL Queries
PL/SQL
MySQL
SQL Server
Misc
Using SQL within Python is quite common, especially for data-related tasks. Python provides multiple libraries to interact with various databases. The most popular one is sqlite3
for SQLite databases, which comes bundled with the standard Python library. For other databases like MySQL, PostgreSQL, or Oracle, you can use libraries such as MySQLdb
, Psycopg2
, and cx_Oracle
respectively.
Below, I'll outline how to use SQL with Python using sqlite3
:
First, ensure you have SQLite and Python installed.
import sqlite3 # Connect to a database (or create it if it doesn't exist) conn = sqlite3.connect('example.db') cursor = conn.cursor() # Create a table cursor.execute(''' CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER ) ''') # Commit the changes and close the connection conn.commit() conn.close()
conn = sqlite3.connect('example.db') cursor = conn.cursor() # Insert a record cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 30)) # Commit and close conn.commit() conn.close()
conn = sqlite3.connect('example.db') cursor = conn.cursor() # Query data cursor.execute("SELECT * FROM users WHERE age > ?", (25,)) rows = cursor.fetchall() for row in rows: print(row) conn.close()
conn = sqlite3.connect('example.db') cursor = conn.cursor() # Update record cursor.execute("UPDATE users SET age = ? WHERE name = ?", (31, "Alice")) # Delete record cursor.execute("DELETE FROM users WHERE name = ?", ("Alice",)) conn.commit() conn.close()
To make sure connections are always closed even if there are exceptions, you can use the with
statement:
with sqlite3.connect('example.db') as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM users") rows = cursor.fetchall() for row in rows: print(row)
For other databases, the general structure remains the same, but the connection method and sometimes the SQL execution methods may differ. Always refer to the respective library's documentation when working with databases other than SQLite in Python.
How to connect Python to SQL databases:
pyodbc
library to connect to SQL databases.import pyodbc connection = pyodbc.connect('Driver={SQL Server};' 'Server=your_server;' 'Database=your_database;' 'UID=your_username;' 'PWD=your_password') cursor = connection.cursor()
Using Python libraries for SQL interaction:
pyodbc
, other popular libraries include pandas
, SQLAlchemy
, and sqlite3
for different database types.import pandas as pd from sqlalchemy import create_engine engine = create_engine('sqlite:///:memory:') df = pd.read_sql_query('SELECT * FROM your_table', engine)
Executing SQL queries in Python:
execute
method.query = 'SELECT column1, column2 FROM your_table WHERE condition' cursor.execute(query)
Python and SQL server connection:
pyodbc
.import pyodbc connection = pyodbc.connect('Driver={SQL Server};' 'Server=your_server;' 'Database=your_database;' 'UID=your_username;' 'PWD=your_password')
Python libraries for SQL database access:
pyodbc
, pymysql
, psycopg2
, or cx_Oracle
for various database connections.import pyodbc import pymysql import psycopg2 import cx_Oracle
Parameterized queries in Python with SQL:
query = 'SELECT * FROM your_table WHERE column = ?' parameters = ('value',) cursor.execute(query, parameters)
Python ORM for SQL databases:
from sqlalchemy import create_engine, Column, Integer, String, MetaData, Table engine = create_engine('sqlite:///:memory:') metadata = MetaData() your_table = Table('your_table', metadata, Column('id', Integer, primary_key=True), Column('name', String), Column('age', Integer)) metadata.create_all(engine)
SQLalchemy and Python for database interactions:
from sqlalchemy import create_engine, Column, Integer, String, MetaData, Table from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:') Session = sessionmaker(bind=engine) session = Session() # Define your ORM classes here session.commit()
Fetching and manipulating SQL results in Python:
fetchone()
or fetchall()
.row = cursor.fetchone() rows = cursor.fetchall() for row in rows: print(row)
Python and SQLite database interaction:
sqlite3
for interaction.import sqlite3 connection = sqlite3.connect('your_database.db') cursor = connection.cursor()
Connecting Python to MySQL databases:
pymysql
library.import pymysql connection = pymysql.connect(host='your_host', user='your_username', password='your_password', database='your_database')
Python and PostgreSQL database integration:
psycopg2
library for connecting to PostgreSQL databases.import psycopg2 connection = psycopg2.connect(host='your_host', user='your_username', password='your_password', database='your_database')
Data visualization with Python and SQL:
matplotlib
, seaborn
, or plotly
to visualize SQL query results.import matplotlib.pyplot as plt import pandas as pd df = pd.read_sql_query('SELECT * FROM your_table', connection) df.plot(kind='bar', x='column1', y='column2') plt.show()
Error handling in Python with SQL interactions:
try: cursor.execute('SELECT * FROM your_table') except Exception as e: print(f'Error: {e}')