使用 SQLAlchemy 将 SQL 数据库表读入 Pandas DataFrame
要仅使用表名将 sql 表读入 DataFrame,而不执行任何查询,我们使用 Pandas 中的read_sql_table()
方法。此函数不支持 DBAPI 连接。
read_sql_table()
Syntax : pandas.read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None)
Parameters :
table_name : (str) Name of SQL table in database.
con : SQLAlchemy connectable or str.
schema : (str) Name of SQL schema in database to query (if database flavor supports this). Default is None
index_col : List of string or string. Column(s) to set as index(MultiIndex). Default is None.
coerce_float : (bool) Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Default is True
parse_dates : (list or dict)
- List of column names to parse as dates.
- Dict of {column_name: format string} where format string is strftime compatible in case of parsing string times or is one of (D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of {column_name: arg dict}, where the arg dict corresponds to the keyword arguments of pandas.to_datetime() Especially useful with databases without native Datetime support, such as SQLite.
columns : List of column names to select from SQL table. Default is None
chunksize : (int) If specified, returns an iterator where chunksize is the number of rows to include in each chunk. Default is None.
Return type : DataFrame
示例 1:
# import the modules
import pandas as pd
from sqlalchemy import create_engine
# SQLAlchemy connectable
cnx = create_engine('sqlite:///contacts.db').connect()
# table named 'contacts' will be returned as a dataframe.
df = pd.read_sql_table('contacts', cnx)
print(df)
输出 :
示例 2:
# import the modules
import pandas as pd
from sqlalchemy import create_engine
# SQLAlchemy connectable
cnx = create_engine('sqlite:///students.db').connect()
# table named 'students' will be returned as a dataframe.
df = pd.read_sql_table('students', cnx)
print(df)
输出 :
示例 3:
# import the modules
import pandas as pd
from sqlalchemy import create_engine
# SQLAlchemy connectable
cnx = create_engine('sqlite:///students.db').connect()
# table named 'employee' will be returned as a dataframe.
df = pd.read_sql_table('employee', cnx)
print(df)
输出 :
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。