我有一些相当大的pandas数据帧,我想使用新的大容量SQL映射通过SQL Alchemy将它们上载到microsoftsql服务器。pandas.to-sql方法虽然不错,但速度很慢。
我写代码有困难。。。
我希望能够向此函数传递一个我正在调用table
的pandas数据帧、一个我正在调用schema
的架构名和一个我正在调用name
的表名。理想情况下,函数将1.)删除已存在的表。2.)创建新表3.)创建映射器4.)使用映射器和pandas数据进行大容量插入。我被困在第三部分。
这是我的(无可否认的粗糙)代码。我正在努力使mapper函数与我的主键一起工作。我不需要主键,但mapper函数需要它。
谢谢你的洞察力。
from sqlalchemy import create_engine Table, Column, MetaData
from sqlalchemy.orm import mapper, create_session
from sqlalchemy.ext.declarative import declarative_base
from pandas.io.sql import SQLTable, SQLDatabase
def bulk_upload(table, schema, name):
e = create_engine('mssql+pyodbc://MYDB')
s = create_session(bind=e)
m = MetaData(bind=e,reflect=True,schema=schema)
Base = declarative_base(bind=e,metadata=m)
t = Table(name,m)
m.remove(t)
t.drop(checkfirst=True)
sqld = SQLDatabase(e, schema=schema,meta=m)
sqlt = SQLTable(name, sqld, table).table
sqlt.metadata = m
m.create_all(bind=e,tables=[sqlt])
class MyClass(Base):
return
mapper(MyClass, sqlt)
s.bulk_insert_mappings(MyClass, table.to_dict(orient='records'))
return
基于@ansonw答案:
我在5秒内插入200000行而不是4分钟
我遇到了一个类似的问题,pd.to-sql花了几个小时上传数据。下面的代码在几秒钟内大量插入了相同的数据。
当时可能已经有了答案,但是我通过整理这个站点上的不同答案并与SQLAlchemy的文档对齐找到了解决方案。
希望这有助于任何人来这里,并想混合熊猫和快速炼金术。
相关问题 更多 >
编程相关推荐