Python,SQLAlchemy,如何只用一个提交指令以有效的方式插入查询

标签 python sql sqlalchemy performance

我正在使用 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()

最佳答案

我认为你最好使用 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

关于Python,SQLAlchemy,如何只用一个提交指令以有效的方式插入查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655605/

相关文章:

python - numpy 中的多维数组乘法

Python 正则表达式组解析具有可能存在或不存在的多个组的输入

python - 使用换行符作为 numpy.savetxt 的分隔符不起作用

php - 将 SQL 上传到公共(public) git 存储库是否安全并建议?

python - 如何在 SQLAlchemy 中定义对继承列的约束?

python - 在 SQLAlchemy 中,如何查询复合主键?

python - 列表理解以从字典中提取元组列表

SQL:从表中选择行序列的最有效方法

sql - SQL FTS和比较语句

python - 如何使用多级/多连接在 SQLAlchemy 中指定表关系?