Python,SQLAlchemy,如何仅通过一条提交指令以一种有效的方式插入查询
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python,SQLAlchemy,如何仅通过一条提交指令以一种有效的方式插入查询,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1541字,纯文字阅读大概需要3分钟。
内容图文
![Python,SQLAlchemy,如何仅通过一条提交指令以一种有效的方式插入查询](/upload/InfoBanner/zyjiaocheng/881/8dfa69ee90a44df0b41b97662fa5f924.jpg)
我正在使用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,如何仅通过一条提交指令以一种有效的方式插入查询全部内容,希望文章能够帮你解决Python,SQLAlchemy,如何仅通过一条提交指令以一种有效的方式插入查询所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。