使用 Pandas 导入多个 SQL 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32912373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:58:04  来源:igfitidea点击:

Importing multiple SQL tables using pandas

pythonsqldatabasepandas

提问by petercj

I have a database that contains multiple tables, and I am trying to import each table as a pandas dataframe. I can do this for a single table as follows:

我有一个包含多个表的数据库,我正在尝试将每个表作为 Pandas 数据框导入。我可以为单个表执行此操作,如下所示:

import pandas as pd
import pandas.io.sql as psql
import pypyodbc

conn = pypyodbc.connect("DRIVER={SQL Server};\
                        SERVER=serveraddress;\
                        UID=uid;\
                        PWD=pwd;\
                        DATABASE=db")

df1 = psql.read_frame('SELECT * FROM dbo.table1', conn)

The number of tables in the database will change, and at any time I would like to be able to import each table into its own dataframe. How can I get all of these tables into pandas?

数据库中表的数量会发生变化,我希望能够随时将每个表导入到自己的数据框中。如何将所有这些表放入Pandas?

回答by elelias

Depending on your SQL server, you can inspect the tables in a database.

根据您的 SQL 服务器,您可以检查数据库中的表。

For example:

例如:

tables_df = pd.read_sql('SELECT table_name FROM database_name', conn)

Now your table names are accessible as a pandas data frame, you just need to parse it out:

现在您的表名可以作为 Pandas 数据框访问,您只需要解析它:

table_name_list = tables_df.table_name

select_template = 'SELECT * FROM {table_name}'
frames_dict = {}
for tname in table_name_list:
    query = select_template.format(table_name = tname)
    frames_dict[tname] = pd.read_sql(query, conn)

Your dictionary frames_dictcontains all the dataframes with the table_name as the key

您的字典frames_dict包含所有以 table_name 为键的数据框