pd.to_sql(table_name, db)这种方法虽然很简单,但是性能特别慢;插入6万条数据,需要将近5分钟
engine = sqla.create_engine('postgresql+psycopg2://user:pwd@IPCLOUDMAP')
df = pd.read_excel(filename, skiprows=0)
df.to_sql('yun_ying_jian_ce_2', engine, index=False, if_exists='append')
优化方法,利用StringIO,和copy_from , 此方法可在1.68s内将数据插入表中
from io import StringIO # 此处有的会使用 from cStringIO import StringIO
engine = sqla.create_engine('postgresql+psycopg2://user:pwd@IPCLOUDMAP')
df = pd.read_excel(filename, skiprows=0)
df.to_sql('yun_ying_jian_ce_2', engine, index=False, if_exists='append')
output = StringIO()
df.to_csv(output, sep='\t', index=False, header=False)
output.getvalue()
output.seek(0)
connection = engine.raw_connection()
cursor = connection.cursor()
cursor.copy_from(output, 'yun_ying_jian_ce_2', null='')
connection.commit()
cursor.close()
注意sqlServer就别想使用 这种方法了,因为pyodbc没有copy_from , copy_from是pg的特性,有哪位大佬解决了sqlServer 使用copy_from,恭候留言
engine = sqla.create_engine('mssql+pyodbc://sa:pwd#@IP:1433/CLOUDMAP?driver=SQL+Server')
AttributeError: 'pyodbc.Cursor' object has no attribute 'copy_from'