为什么在进行 UPDATE 时需要显式提交?

发布于 2024-09-02 10:46:09 字数 297 浏览 2 评论 0原文

这是我的代码:

import cx_Oracle

conn = cx_Oracle.connect(usr, pwd, url)
cursor = conn.cursor()
cursor.execute("UPDATE SO SET STATUS='PE' WHERE ID='100'")
conn.commit()

如果我删除 conn.commit(),则表不会更新。但对于 select 语句,我不需要 conn.commit()。我很好奇为什么?

Here's my code:

import cx_Oracle

conn = cx_Oracle.connect(usr, pwd, url)
cursor = conn.cursor()
cursor.execute("UPDATE SO SET STATUS='PE' WHERE ID='100'")
conn.commit()

If I remove the conn.commit(), the table isn't updated. But for select statements, I don't need that conn.commit(). I'm curious why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苍白女子 2024-09-09 10:46:09

DB-API 规范要求连接到数据库开始一个新事务,默认情况下。您必须提交以确认所做的任何更改,或回滚以放弃它们。

请注意,如果数据库支持自动提交功能,则必须首先关闭该功能。

纯 SELECT 语句,因为它们从未对数据库进行任何更改,所以不必提交更改。

The DB-API spec requires that connecting to the database begins a new transaction, by default. You must commit to confirm any changes you make, or rollback to discard them.

Note that if the database supports an auto-commit feature, this must be initially off.

Pure SELECT statements, since they never make any changes to the database, don't have to have their changes committed.

雨落□心尘 2024-09-09 10:46:09

其他人已经解释了为什么 SELECT 语句不需要提交。我只是想指出您可以利用 Connection 对象以避免必须自己手动执行提交:

import cx_Oracle

with cx_Oracle.connect(usr, pwd, url) as conn:
    conn.autocommit = True
    cursor = conn.cursor()
    cursor.execute("UPDATE SO SET STATUS='PE' WHERE ID='100'")
    cursor.close()

当同一连接中有多个 INSERT、UPDATE 和 DELETE 语句时,这尤其有用。

Others have explained why a commit is not necessary on a SELECT statement. I just wanted to point out you could utilize the autocommit property of the Connection object to avoid having to manually execute commit yourself:

import cx_Oracle

with cx_Oracle.connect(usr, pwd, url) as conn:
    conn.autocommit = True
    cursor = conn.cursor()
    cursor.execute("UPDATE SO SET STATUS='PE' WHERE ID='100'")
    cursor.close()

This is especially useful when you have multiple INSERT, UPDATE, and DELETE statements within the same connection.

晨曦÷微暖 2024-09-09 10:46:09

commit用于告诉数据库保存当前事务中的所有更改。

Select 不会更改任何数据,因此无需保存任何内容,也无需提交任何内容。

请参阅 wikipedia 了解事务

commit is used to tell the database to save all the changes in the current transaction.

Select does not change any data so there is nothing to save and thus nothing to commit

See wikipedia for transactions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文