如何从数据库中动态获取表?

How to dynamically fetch tables from database?

有一个数据库有几个 table。我正在尝试编写一个函数来获取它们而不明确指示 table 名称。

我有这样的功能:

def get_fb_sql_tables():
    try:
        fb_data_table = pd.read_sql('SELECT * FROM FB_Data', con=engine)
        fb_meta_table = pd.read_sql('SELECT * FROM FB_Meta', con=engine)
        fb_basic_table = pd.read_sql('SELECT * FROM FB_Basic', con=engine)

        fb_data_table.reset_index(drop=True).drop_duplicates()
        fb_meta_table.reset_index(drop=True).drop_duplicates()
        fb_basic_table.reset_index(drop=True).drop_duplicates()

        return fb_data_table, fb_meta_table, fb_basic_table

    except Exception as e:
            logging.error("Exception occurred, check def get_fb_sql_tables", exc_info=True)

但我正在尝试制作这样的功能

def get_sql_tables(*tables):
    sql_tables = []

    try:
        for table in tables():
            table = pd.read_sql('SELECT * FROM {}'.format(table), con=engine)
            table .reset_index(drop=True).drop_duplicates()
            logging.info('Got {} tables successfully'.format(table))
            sql_tables.append(table)
            return sql_tables

    except Exception as e:
            logging.error("Exception occurred, check def get_sql_tables", exc_info=True)



sql_tables = ['FB_Data','FB_Meta']

for table in sql_tables:
    print(get_sql_tables(table))

我试过 *args**kwargs 但它不起作用。

它 returns None 个对象。

如果您的代码中有 for 循环,则不必解压 table 姓名列表:

import logging
import pandas as pd

# no need to unpack the list if you have for loop
def get_sql_tables(tables):
    sql_tables = []

    try:
        for table in tables:
            # avoid same names for loop variable and inside the loop
            table_res = pd.read_sql('SELECT * FROM {}'.format(table), con=engine)
            table_res.reset_index(drop=True).drop_duplicates()
            logging.info('Got {} tables successfully'.format(table))
            sql_tables.append(table_res)
        # return need to be outside of the loop
        return sql_tables
    # generic exception is not a good practice - try to be specific
    except Exception as e:
        logging.error("Exception occurred, check def get_sql_tables", exc_info=True)

# no need for second for loop
sql_tables = ['FB_Data', 'FB_Meta']
print(get_sql_tables(sql_tables))