社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何将python 3中的数据快速插入sqlserver?

fcol • 7 年前 • 2769 次点击  

我很难将python3中的大量数据快速插入到sql server中。

目标表有9列,3个索引和1个主键。

下面的代码可以工作,但是比我想要的慢很多。见以下时间安排:

-- 1,000 records
In [35]: %time connection_factory.executemany(sql, args)
CPU times: user 30.2 ms, sys: 40.9 ms, total: 71.1 ms
Wall time: 3.54 s

-- 5,000 records
In [46]: %time connection_factory.executemany(sql, args)
CPU times: user 110 ms, sys: 55.8 ms, total: 166 ms
Wall time: 17 s

我试过使用sql_炼金术,目前正在使用turbodbc,但对其他任何工作速度更快的方法都是开放的。

下面是我的代码示例

from turbodbc import connect, make_options

class ConnectionFactory:
def __init__(self):
    self.connection = self.initialize()

@staticmethod
def initialize():
    options = make_options(autocommit=True)
    return connect(driver="FREETDS",
                   server="",
                   port="",
                   database="",
                   uid="",
                   pwd="",
                   turbodbc_options=options)

def execute(self, query, params=None):
    try:
        cursor = self.connection.cursor()
        cursor.execute(query, params)
    except Exception as e:
        print(e)
    finally:
        cursor.close()
        return

def executemany(self, query, params=None):
    try:
        cursor = self.connection.cursor()
        cursor.executemany(query, params)
    except Exception as e:
        print(e)
    finally:
        cursor.close()
        return


sql = """
INSERT INTO table1 (value1,
                    value2,
                    value3,
                    value4,
                    value5,
                    value6,
                    value7)
VALUES (?, ?, ?, ?, ?, ?, ?); """

args = df.to_records().tolist()
connection_factory = ConnectionFactory()
connection_factory.executemany(sql, args)

是否有人熟悉这种sql server和python的精确组合,可以为我指明正确的方向?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39572
文章 [ 2 ]  |  最新文章 7 年前