微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 将大型Pandas DataFrames写入SQL Server数据库

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

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

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

self._session_factory.engine.execute(
    TimeSeriesResultValues.__table__.insert(),
    data)
# 'data' is a list of dictionaries.

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

(pyodbc.IntegretyError) ('23000', "[23000] [FreeTDS][sql Server]Cannot
insert the value NULL into the column...

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

编辑:

这是我要离开的例子:

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")

解决方法:

我有一些令人遗憾的消息,sqlAlchemy实际上并没有为sql Server实现批量导入,它实际上只是执行与to_sql相同的缓慢的单个INSERT语句.我想说你最好的办法是尝试使用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')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐