使用SQLAlchemy将SQL数据库表读入Pandas DataFrame中

使用SQLAlchemy将SQL数据库表读入Pandas DataFrame中

为了将sql表读入DataFrame,只使用表名,而不执行任何查询,我们使用Pandas的read_sql_table()方法。这个函数不支持DBAPI连接。

read_sql_table()

语法 :

pandas.read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None)
Python

参数 :

table_name : (str) 数据库中SQL表的名称。

con : SQLAlchemy可连接或str。

schema : (str) 要查询的数据库中的SQL模式的名称(如果数据库类型支持的话)。默认为无

index_col : 字符串或字符串的列表。要设置为索引的列(MultiIndex)。默认为无。

coerce_float : (bool) 试图将非字符串、非数字对象(如decimal.Decimal)的值转换成浮点。默认为真

parse_dates : (list or dict)

  • 要解析为日期的列名列表。
  • Dict of {column_name: format string},其中格式字符串在解析字符串时间的情况下与strftime兼容,在解析整数时间戳的情况下是(D, s, ns, ms, us)之一。
  • Dict of {column_name: arg dict},其中arg dict对应于pandas.to_datetime()的关键字参数,对没有本地Datetime支持的数据库特别有用,比如SQLite

columns :从SQL表中选择的列名列表。默认为无

chunksize : (int) 如果指定,返回一个迭代器,其中chunksize是每个块中包含的行数。默认为无。

返回类型:数据框架

例子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)
Python

输出 :
使用SQLAlchemy将SQL数据库表读入Pandas DataFrame中

例子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)
Python

输出 :
使用SQLAlchemy将SQL数据库表读入Pandas DataFrame中

例子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)
Python

输出 :
使用SQLAlchemy将SQL数据库表读入Pandas DataFrame中

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册