我正在努力实现以下目标.我想创建一个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)
现在我可以像这样访问所有表:
my_db = sql2df('mydb')
my_db.table1
我想要的东西:
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 @R_956_4045@ion_schema.TABLES WHERE TABLE_SCHEMA = '%s' """ % self.db)
<some kind of iteration that gives back all the tables in df as class attributes>
建议最受欢迎……
解决方法:
我会使用sqlAlchemy:
engine = sqlalchemy.create_engine("MysqL+MysqLdb://root:[email protected]/%s" % db)
注意syntax是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
这会返回一个字典,但您也可以将它们作为类属性(例如,通过更新类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]
在pandas 0.14中,sql代码已经被重写为带引擎,而IIRC有所有表的助手和读取所有表(使用read_sql(table_name)).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。