read_sql
read_sql runs a SQL query and returns the result as a DataFrame.
In this page:
Syntax
df = pd.read_sql("SELECT * FROM table_name", connection)
read_sql
pd.read_sql(query, connection) works with a DBAPI connection such as sqlite3 or an SQLAlchemy engine. Use params for safe parameter binding. The reverse, to_sql, writes a DataFrame into a table.
Note:
Use parameters (params=) instead of building SQL with string formatting.
Example: read_sql
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
pd.DataFrame({"id": [1, 2, 3], "name": ["Ann", "Bob", "Cy"]}).to_sql("users", con, index=False)
print(pd.read_sql("SELECT * FROM users WHERE id > ?", con, params=(1,)))
con.close()
# Output:
# id name
# 0 2 Bob
# 1 3 Cy
Related Topics
Common Mistakes
- Building queries with string formatting
- Forgetting to close the connection
- Not specifying if_exists in to_sql
Chapter Summary
- read_sql runs a query into a DataFrame
- Works with sqlite3 connections
- to_sql writes tables
- Use params for safety
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: