【问题标题】:Python, SQLAlchemy, how to insert queries in an efficient way with only one commit instructionPython,SQLAlchemy,如何仅使用一条提交指令以有效的方式插入查询
【发布时间】:2013-07-13 09:33:13
【问题描述】:

我正在使用 SQLAlchemy,并且我的插入函数工作正常。但是,我希望并且我需要它高效,因此由于我在“for 循环”中插入,我想在程序执行结束时只提交一次。

我不确定,这种想法是否适用于 SQLAlchemy,所以请告诉我正确、有效的方法。

我的代码将从 for 循环中调用 insert_query 函数。我不返回在函数调用中创建的查询对象。

def insert_query(publicId, secret, keyhandle, secretobj):

    #creates the query object 
    sql = secretobj.insert().values(public_id=publicId, keyhandle=keyhandle, secret=secret)
    #insert the query
    result = connection.execute(sql)

    return result

#####################
# CALL INSERT BELOW #
#####################


#walk across the file system to do some stuff
for root, subFolders, files in os.walk(path):
    if files:

        do_some_stuff_that_produce_output_for_insert_query()

        #########################
        # here i call my insert #
        #########################
        if not insert_query(publicId, secret, keyhandle, secretobj):
            print "WARNING: could not insert %s" % publicId


#close sqlalchemy
connection.close()

【问题讨论】:

    标签: python sql sqlalchemy performance


    【解决方案1】:

    我认为你最好使用 executemany。

    def make_secret(files):
        # You'd have to define how you generate the dictionary to insert.
        # These names should match your table column names.
        return {
            'public_id': None,
            'secret': None,
            'keyhandle': None,
        }
    # You can make the whole list of rows to insert at once.
    secrets = [make_secret(files) for root, subFolders, files in os.walk(path) if files]
    # Then insert them all like this
    connection.execute(secretobj.insert(), secrets)
    

    executemany 在本节的第二部分解释:

    http://docs.sqlalchemy.org/en/rel_0_8/core/tutorial.html#executing-multiple-statements

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 2013-08-10
      • 2021-03-11
      • 2013-05-15
      • 2022-01-13
      • 2021-01-18
      • 1970-01-01
      相关资源
      最近更新 更多