Pandas pd.read_sql() function
read_sql() is a function in the pandas library for reading data from a database. It supports SQL queries and direct reading of database tables.
Databases are core components of enterprise applications, storing large amounts of business data.read_sql() It can connect to various types of databases (such as MySQL, PostgreSQL, SQLite, etc.), execute SQL queries, and convert the results into a DataFrame for subsequent data analysis and processing.
Basic syntax and parameters
Syntax format
pandas.read_sql(sql, con, index_col=None, coerce_float=True, params=None,
parse_dates=None, chunksize=None, dtype=None, ...)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| sql | str or SQLAlchemy Selectable | SQL query string or table name | Required |
| con | sqlalchemy engine, or sqlite3 connection | Database connection object | Required |
| index_col | str, list of str | Column name to use as the row index | None |
| coerce_float | bool | Whether to try converting numeric strings to floats | True |
| params | list, tuple, dict | Parameters for a parameterized SQL query | None |
| parse_dates | list, dict | Columns to parse as dates | None |
| chunksize | int | Size of the iterator returned when chunking | None |
Return Value
- Return Type:
pd.DataFrameor Iterator[DataFrame] - When
chunksizeWhen it is None, a single DataFrame is returned. - When set,
chunksizean iterator is returned, yielding a DataFrame on each iteration.
Example
Through the following examples, fully master read_sql() its various usages.
Example 1: Using a SQLite database
SQLite is a lightweight embedded database that needs no separate database server, making it ideal for learning and testing.
Example
import
pandas
as
pd
import
sqlite3
Create an in-memory SQLite database and insert test data
conn
=
sqlite3.
connect
(
':memory:'
)
Create a table and insert data
cursor
=
conn.
cursor
(
)
Create an employees table
cursor.
execute
(
'''
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
city TEXT,
salary INTEGER
)
'''
)
Insert test data
employees_data
=
[
(
1
,
'Tom'
,
28
,
'Beijing'
,
8000
)
,
(
2
,
'Jerry'
,
35
,
'Shanghai'
,
12000
)
,
(
3
,
'Mike'
,
42
,
'Guangzhou'
,
15000
)
,
(
4
,
'Lucy'
,
26
,
'Shenzhen'
,
7000
)
,
(
5
,
'John'
,
31
,
'Beijing'
,
9500
)
]
cursor.
executemany
(
'INSERT INTO employees VALUES (?, ?, ?, ?, ?)'
,
employees_data
)
conn.
commit
(
)
Example 1a: Executing an SQL query and reading data
sql: SQL query string (required)
con: database connection object (required)
query
=
"SELECT name, age, city, salary FROM employees WHERE salary > 8000"
df_query
=
pd.
read_sql
(
query
,
conn
)
(
"Execute SQL query:"
)
(
df_query
)
(
)
Example 1b: Reading an entire table directly
You can pass a table name as the sql argument
df_table
=
pd.
read_sql
(
'employees'
,
conn
)
(
"Read entire table:"
)
(
df_table
)
(
)
Example 1c: Setting an index with index_col
df_indexed
=
pd.
read_sql
(
'employees'
,
conn
,
index_col
=
'id'
)
(
"Set index column:"
)
(
df_indexed
)
Expected output:
Execute SQL query:
name age city salary
0 Tom 28 Beijing 8000
1 Jerry 35 Shanghai 12000
2 Mike 42 Guangzhou 15000
chunksize
空字符串 NaN NaN NaN NaN
3 Lucy 26 Shenzhen 7000
4 John 31 Beijing 9500
# Read the entire table:
id name age city salary
0 1 Tom 28 Beijing 8000
1 pandas 的 read_sql() 和 read_sql_query() 函数说明 read_sql() 是统一的接口,可以接受 SQL 语句或表名 read_sql_query() 只接受 SQL 语句,返回查询结果 read_sql_table() 只接受表名,返回整个表
2 3 Mike 42 Guangzhou 15000
3 4 Lucy 26 Shenzhen 7000
4 5 John 31 Beijing 9500
Set index column:
name age city salary
id
1 Tom 28 Beijing 8000
2 Jerry 35 Shanghai 12000
3 Mike 42 Guangzhou 15000
4 Lucy 26 Shenzhen 7000
5 John 31 Beijing 9500
Code analysis:
read_sql()It accepts an SQL query string as the first argument.conThe argument must be a database connection object, which can be a sqlite3, SQLAlchemy, or similar connection.- You can pass a table name directly to read the entire table.
index_colThe parameter can specify a column as the row index.
Example 2: Connecting to a database with SQLAlchemy
SQLAlchemy is the most popular ORM framework in Python and supports connections to many databases.
Example
import
pandas
as
pd
from
sqlalchemy
import
create_engine
,
text
Create an in-memory SQLite database with SQLAlchemy
engine
=
create_engine
(
'sqlite:///:memory:'
)
Create test data
with
engine.
connect
(
)
as
conn:
Create a products table
conn.
execute
(
text
(
'''
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
category TEXT,
price REAL,
stock INTEGER
)
'''
)
)
Insert data
products_data
=
[
(
'A'
,
'Electronics'
,
999.99
,
50
)
,
(
'B'
,
'Electronics'
,
499.99
,
100
)
,
(
'C'
,
'Clothing'
,
29.99
,
200
)
,
(
'D'
,
'Food'
,
5.99
,
500
)
,
(
'E'
,
'Books'
,
19.99
,
150
)
]
conn.
execute
(
text
(
'''
INSERT INTO products (name, category, price, stock) VALUES (?, ?, ?, ?)
'''
)
,
products_data
)
conn.
commit
(
)
Example 2a: Reading data with a SQLAlchemy engine
query
=
"SELECT * FROM products WHERE category = :category"
df_params
=
pd.
read_sql
(
query
,
engine
,
params
=
{
'category'
:
'Electronics'
}
Parameterized queries to prevent SQL injection
)
(
"Use parameterized query:"
)
(
df_params
)
(
)
Example 2b: Reading directly with a table name
df_all
=
pd.
read_sql
(
'products'
,
engine
)
(
"Read entire table:"
)
(
df_all
)
(
)
Example 2c: Trying other database connections (using MySQL as an example)
Note: the corresponding database driver must be installed
pip install pymysql # MySQL
pip install psycopg2 # PostgreSQL
MySQL connection example
engine_mysql = create_engine('mysql+pymysql://username:password@host/database')
df_mysql = pd.read_sql('SELECT * FROM table_name', engine_mysql)
(
"Note: actually connecting to MySQL/PostgreSQL requires the corresponding driver"
)
Expected output:
Using parameterized queries:
id name category price stock
0 1 A Electronics 999.99 50
的 read_sql() 配对 write_frame() 已弃用,使用 to_sql() 方法替代 to_sql() 可以将 DataFrame 写入数据库表
2 2 B Electronics 499.99 100
# Read the entire table:
id 名称 类别 价格 库存
0 1 A Electronics 999.99 50
1 2 B ... 读取 499. 参数 100
2 3 C Clothing 29.99 200
3 4 配对 Food 5.99 500
4 5 E Books 19.99 150
Code analysis:
- SQLAlchemy provides a unified database connection interface supporting MySQL, PostgreSQL, Oracle, and other databases.
paramsThe parameter is used for parameterized queries and can prevent SQL injection attacks.- Use SQLAlchemy's
create_engine()to create a database engine.
Example 3: Chunked reading and processing of large data
When a query returns a large amount of data, you can read it in chunks to save memory.
Example
import
pandas
as
pd
import
sqlite3
Create a large amount of test data
conn
=
sqlite3.
connect
(
'test_large.db'
)
cursor
=
conn.
cursor
(
)
Create a table
cursor.
execute
(
'''
CREATE TABLE large_table (
id INTEGER PRIMARY KEY,
value INTEGER,
category TEXT
)
'''
)
Insert 10,000 test records
import
random
large_data
=
[
(
i
,
random
.
randint
(
1
,
1000
)
,
random
.
choice
(
[
'A'
,
'B'
,
'C'
]
)
)
for
i
in
range
(
1
,
10001
)
]
cursor.
executemany
(
'INSERT INTO large_table VALUES (?, ?, ?)'
,
large_data
)
conn.
commit
(
)
Example 3a: Reading data in chunks
The chunksize parameter specifies how many rows are returned each time
(
"Read data in chunks:"
)
chunks
=
pd.
read_sql
(
'SELECT * FROM large_table'
,
conn
,
chunksize
=
2000
)
Use a generator to process each chunk
for
i
,
chunk
in
enumerate
(
chunks
)
:
(
f
"Chunk {i+1}: {len(chunk)} rows"
)
(
f
" Number of category='A' in this chunk: {len(chunk[chunk['category'] == 'A'])}"
)
(
)
Example 3b: Aggregation (combining all chunks)
If you need global statistics, you can combine all chunks
all_chunks
=
[
]
chunks
=
pd.
read_sql
(
'SELECT category, SUM(value) as total FROM large_table GROUP BY category'
,
conn
,
chunksize
=
1000
)
for
chunk
in
chunks:
all_chunks.
append
(
chunk
)
Combine results
result
=
pd.
concat
(
all_chunks
,
ignore_index
=
True
)
(
"Aggregated result:"
)
(
result
)
(
)
Close the Connection
conn.
close
(
)
Clean up test files
import
os
os
.
remove
(
'test_large.db'
)
(
"Test database cleaned up"
)
Expected output:
Chunked data reading:
块 1: 2000 行
块 读取 category='A' 的数据
...
块 5: 2000 行
该块 category='A' 的数量: 约 667 行
Aggregated results:
category total
0 A 1687500
1 B 1678250
2 Chunks 读取 约 665 行
Code analysis:
chunksizeThe parameter returns an iterator that yields a DataFrame on each iteration.- Chunked reading is suitable for large datasets and helps avoid running out of memory.
- For aggregate queries, you can use
pd.concat()to combine the results of all chunks.
Notes
- Use
read_sql()The corresponding database driver must be installed. - SQLite needs no additional installation and works out of the box.
- MySQL requires
pymysqlormysql-connector-python:pip install pymysql。 - PostgreSQL requires
psycopg2:pip install psycopg2。 - Use parameterized queries (
paramsparameters) to prevent SQL injection attacks. - When reading a large table, use
chunksizethe parameter to read in chunks.
Summary
read_sql() is the core function in pandas for connecting to a database and reading data. It can execute arbitrary SQL queries and convert the results into DataFrame format.
In real data analysis work, databases are the core storage for enterprise data. Mastering read_sql() lets you fetch data directly from a database for analysis. Note the use of parameterized queries for security and chunked reading for large datasets.
Common Pandas functions