Python类将数据库中的所有表转换为pandas数据帧

bow*_*lby 4 python mysql pandas

我正在努力实现以下目标.我想创建一个python类,将数据库中的所有表转换为pandas数据帧.

我就是这样做的,这不是很通用的......

class sql2df():
    def __init__(self, db, password='123',host='127.0.0.1',user='root'):
        self.db = db

        mysql_cn= MySQLdb.connect(host=host,
                        port=3306,user=user, passwd=password, 
                        db=self.db)

        self.table1 = psql.frame_query('select * from table1', mysql_cn)
        self.table2 = psql.frame_query('select * from table2', mysql_cn)
        self.table3 = psql.frame_query('select * from table3', mysql_cn)
Run Code Online (Sandbox Code Playgroud)

现在我可以像这样访问所有表:

my_db = sql2df('mydb')
my_db.table1
Run Code Online (Sandbox Code Playgroud)

我想要的东西:

class sql2df():
    def __init__(self, db, password='123',host='127.0.0.1',user='root'):
        self.db = db

        mysql_cn= MySQLdb.connect(host=host,
                        port=3306,user=user, passwd=password, 
                        db=self.db)
        tables = (""" SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = '%s' """ % self.db)
        <some kind of iteration that gives back all the tables in df as class attributes>
Run Code Online (Sandbox Code Playgroud)

建议最受欢迎......

And*_*den 5

我会使用SQLAlchemy:

engine = sqlalchemy.create_engine("mysql+mysqldb://root:123@127.0.0.1/%s" % db)
Run Code Online (Sandbox Code Playgroud)

注意语法是dialect + driver:// username:password @ host:port/database.

def db_to_frames_dict(engine):
    meta = sqlalchemy.MetaData()
    meta.reflect(bind=engine)
    tables = meta.sorted_tables
    return {t: pd.read_sql('SELECT * FROM %s' % t.name,
                           engine.raw_connection())
                   for t in tables}
    # Note: frame_query is depreciated in favor of read_sql
Run Code Online (Sandbox Code Playgroud)

这会返回一个字典,但您也可以将这些作为类属性(例如,通过更新类dict和__getitem__)

class SQLAsDataFrames:
    def __init__(self, engine):
        self.__dict__ = db_to_frames_dict(engine)  # allows .table_name access
    def __getitem__(self, key):                    # allows [table_name] access
        return self.__dict__[key]
Run Code Online (Sandbox Code Playgroud)

在pandas 0.14中,sql代码已经被重写为带引擎,而IIRC有所有表的助手和读取所有表(使用read_sql(table_name)).