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



有一个包含多个表的数据库。我正在尝试编写一个函数来获取它们,而无需明确指示表名。

我有一个这样的函数:

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但它不起作用。

它返回 None 对象。

如果你的代码中有 for 循环,你不必解压缩表名列表:

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))

最新更新