例子编号 | 描述 | 函数/参数 | 预期结果描述 |
---|---|---|---|
1 | 读取整个表 | read_sql_table |
整个表的前 5 行 |
2 | 执行 SQL 查询 | read_sql_query |
根据查询条件的前 5 行 |
3 | 读取特定列 | columns |
特定列的前 5 行 |
4 | 读取元数据定义的表 | MetaData , reflect |
使用元数据的前 5 行 |
5 | 读取结果集的前几行 | chunksize |
查询结果的前 10 行 |
6 | 读取数据库视图 | read_sql_table |
视图的前 5 行 |
7 | 读取数据库临时表 | read_sql_table |
临时表的前 5 行 |
8 | 指定列的数据类型 | dtype |
指定数据类型列的前 5 行 |
9 | 使用索引列 | index_col |
以特定列索引的前 5 行 |
10 | 过滤数据并读取 | SQL 查询过滤 | 过滤后结果的前 5 行 |
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('sqlite:///mydatabase.db') # 示例为 SQLite 数据库
df = pd.read_sql_table('my_table', con=engine)
print(df.head())
query = "SELECT * FROM my_table WHERE column1 = 'value'"
df = pd.read_sql_query(query, con=engine)
print(df.head())
columns = ['column1', 'column2']
df = pd.read_sql_table('my_table', con=engine, columns=columns)
print(df.head())
from sqlalchemy import MetaData
metadata = MetaData(bind=engine)
metadata.reflect()
df = pd.read_sql_table('my_table', con=engine, schema=metadata)
print(df.head())
df = pd.read_sql_query(query, con=engine, chunksize=10)
print(next(df).head()) # 使用 chunksize 需要迭代结果
df = pd.read_sql_table('my_view', con=engine)
print(df.head())
df = pd.read_sql_table('temp_my_table', con=engine)
print(df.head())
dtypes = {'column1': int, 'column3': 'category'}
df = pd.read_sql_table('my_table', con=engine, dtype=dtypes)
print(df.head())
df = pd.read_sql_table('my_table', con=engine, index_col='id_column')
print(df.head())
query = "SELECT * FROM my_table WHERE column2 > 100"
df = pd.read_sql_query(query, con=engine)
print(df.head())