将大型Pandas DataFrame写入SQL Server数据库

den*_*aar 11 python sql-server sqlalchemy pandas

我有74个相对较大的Pandas DataFrames(大约34,600行和8列),我试图尽快插入SQL Server数据库.在做了一些研究之后,我了解到良好的ole pandas.to_sql函数对于SQL Server数据库中的大型插入是不利的,这是我采用的最初方法(非常慢 - 应用程序完成的时间差不多一小时,大约4分钟时使用mysql数据库.)

这篇文章以及许多其他StackOverflow帖子都有助于我指出正确的方向,但是我遇到了障碍:

我试图使用SQLAlchemy的Core而不是ORM,原因在上面的链接中解释.所以,我的数据帧转换为字典,使用pandas.to_dict,然后做一个execute()insert():

self._session_factory.engine.execute(
    TimeSeriesResultValues.__table__.insert(),
    data)
# 'data' is a list of dictionaries.
Run Code Online (Sandbox Code Playgroud)

问题是insert没有得到任何值 - 它们显示为一堆空括号,我得到这个错误:

(pyodbc.IntegretyError) ('23000', "[23000] [FreeTDS][SQL Server]Cannot
insert the value NULL into the column...
Run Code Online (Sandbox Code Playgroud)

我传入的词典列表中有值,所以我无法弄清楚为什么值没有显示出来.

编辑:

这是我要离开的例子:

def test_sqlalchemy_core(n=100000):
    init_sqlalchemy()
    t0 = time.time()
    engine.execute(
        Customer.__table__.insert(),
        [{"name": 'NAME ' + str(i)} for i in range(n)]
    )
    print("SQLAlchemy Core: Total time for " + str(n) +
        " records " + str(time.time() - t0) + " secs")
Run Code Online (Sandbox Code Playgroud)

max*_*moo 12

我有一些令人遗憾的消息,SQLAlchemy实际上并没有实现SQL Server的批量导入,它实际上只是执行相同的缓慢的单个INSERT语句to_sql.我想说你最好的选择是使用bcp命令行工具尝试编写一些东西.这是我过去使用的脚本,但不保证:

from subprocess import check_output, call
import pandas as pd
import numpy as np
import os

pad = 0.1
tablename = 'sandbox.max.pybcp_test'
overwrite=True
raise_exception = True
server = 'P01'
trusted_connection= True
username=None
password=None
delimiter='|'
df = pd.read_csv('D:/inputdata.csv', encoding='latin', error_bad_lines=False)



def get_column_def_sql(col):
   if col.dtype == object:
      width = col.str.len().max() * (1+pad)
      return '[{}] varchar({})'.format(col.name, int(width)) 
   elif np.issubdtype(col.dtype, float):
      return'[{}] float'.format(col.name) 
   elif np.issubdtype(col.dtype, int):
      return '[{}] int'.format(col.name) 
   else:
      if raise_exception:
         raise NotImplementedError('data type {} not implemented'.format(col.dtype))
      else:
         print('Warning: cast column {} as varchar; data type {} not implemented'.format(col, col.dtype))
         width = col.str.len().max() * (1+pad)
         return '[{}] varchar({})'.format(col.name, int(width)) 

def create_table(df, tablename, server, trusted_connection, username, password, pad):         
    if trusted_connection:
       login_string = '-E'
    else:
       login_string = '-U {} -P {}'.format(username, password)

    col_defs = []
    for col in df:
       col_defs += [get_column_def_sql(df[col])]

    query_string = 'CREATE TABLE {}\n({})\nGO\nQUIT'.format(tablename, ',\n'.join(col_defs))       
    if overwrite == True:
       query_string = "IF OBJECT_ID('{}', 'U') IS NOT NULL DROP TABLE {};".format(tablename, tablename) + query_string


    query_file = 'c:\\pybcp_tempqueryfile.sql'
    with open (query_file,'w') as f:
       f.write(query_string)

    if trusted_connection:
       login_string = '-E'
    else:
       login_string = '-U {} -P {}'.format(username, password)

    o = call('sqlcmd -S {} {} -i {}'.format(server, login_string, query_file), shell=True)
    if o != 0:
       raise BaseException("Failed to create table")
   # o = call('del {}'.format(query_file), shell=True)


def call_bcp(df, tablename):   
    if trusted_connection:
       login_string = '-T'
    else:
       login_string = '-U {} -P {}'.format(username, password)
    temp_file = 'c:\\pybcp_tempqueryfile.csv'

    #remove the delimiter and change the encoding of the data frame to latin so sql server can read it
    df.loc[:,df.dtypes == object] = df.loc[:,df.dtypes == object].apply(lambda col: col.str.replace(delimiter,'').str.encode('latin'))
    df.to_csv(temp_file, index = False, sep = '|', errors='ignore')
    o = call('bcp sandbox.max.pybcp_test2 in c:\pybcp_tempqueryfile.csv -S "localhost" -T -t^| -r\n -c')
Run Code Online (Sandbox Code Playgroud)


小智 5

这只是最近更新为 SQLAchemy ver: 1.3.0 以防其他人需要知道。应该使您的 dataframe.to_sql 语句更快。

https://docs.sqlalchemy.org/en/latest/changelog/migration_13.html#support-for-pyodbc-fast-executemany

engine = create_engine( "mssql+pyodbc://scott:tiger@mssql2017:1433/test?driver=ODBC+Driver+13+for+SQL+Server", fast_executemany=True )