gpt4 book ai didi

python - 使用 MySQLdb 多次执行

转载 作者:可可西里 更新时间:2023-11-01 08:21:08 27 4
gpt4 key购买 nike

我有一个 python 脚本,可以将大约十个 INSERT 插入到 MySQL 数据库中。这是它当前的结构:

conn = MySQLdb.connect (host = DB_HOST,
port = DB_PORT,
user = DB_USER,
passwd = DB_PASSWORD,
db = DB_NAME)
cursor = conn.cursor()
cursor.execute("INSERT INTO...")
# do some stuff, then another INSERT
cursor.execute("INSERT INTO...")
# do some other stuff, then another INSERT
cursor.execute("INSERT INTO...")
etc...
conn.commit()
cursor.close()
conn.close()

以上是进行多次插入的正确方法,还是我应该在每次 INSERT 后关闭光标?我应该在每次 INSERT 之后执行 commit 吗?

最佳答案

should I be closing the cursor after each INSERT?

没关系。游标被巧妙地重用。

您可以关闭它们以非常小心地保护您的资源。

这样做。

from contextlib import closing
with closing( conn.cursor() ) as cursor:
cursor.execute("INSERT INTO...")

这确保无论发生何种异常,游标都会关闭。

Should I be doing a commit after each INSERT?

这取决于您的应用程序预期做什么。

如果它是一个“全有或全无”的命题,那么你只做一次提交。所有的插入都是好的,或者没有一个是好的。

如果部分结果是可接受的,那么您可以在每次插入后提交。

关于python - 使用 MySQLdb 多次执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9352089/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com