Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,SQLAlchemy,如何用一条提交指令高效地插入查询_Python_Sql_Sqlalchemy_Performance - Fatal编程技术网

Python,SQLAlchemy,如何用一条提交指令高效地插入查询

Python,SQLAlchemy,如何用一条提交指令高效地插入查询,python,sql,sqlalchemy,performance,Python,Sql,Sqlalchemy,Performance,我正在使用SQLAlchemy,我的插入函数工作正常。然而,我希望并且我需要它是有效的,因此,由于我正在“for循环”中插入,我只希望在程序执行结束时提交一次 我不确定,这种想法适用于SQLAlchemy,所以请就正确、有效的方法向我提供建议 我的代码将从for循环调用insert\u查询函数。我不返回在函数调用中创建的查询对象 def insert_query(publicId, secret, keyhandle, secretobj): #creates the query ob

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

我不确定,这种想法适用于SQLAlchemy,所以请就正确、有效的方法向我提供建议

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

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

我认为你最好使用ExecuteMy

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)
本节第二部分解释了执行方式: