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

标签 python database args keyword-argument

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

我有一个这样的函数:

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

关于python - 如何从数据库动态获取表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57848667/

相关文章:

python - 如何通过遍历 __init__ 参数来创建实例属性?

python - 在 *args 中传递一个元组

java - args.length 和命令行参数

python - 导航标题没有很好地对齐并且导航栏有点太粗了?

Python MySQLdb 从另一个数据库中选择并插入

python - 函数参数默认值等于另一个参数

mysql - 两个数据库的列作为外键引用

python - 如何在 Heroku 上使用 New Relic 记录部署

mysql - MySQL 表中的列顺序是否重要?

sql - Flask/Sqlalchemy 的初始数据