【问题标题】:Python | SQLite3: Is commit used on the connect or cursor?蟒蛇 | SQLite3:提交是在连接还是游标上使用?
【发布时间】:2018-10-29 23:21:52
【问题描述】:

我正在通过一本名为 Practical Programming: 2nd Edition 的书学习 python 和 sqlite3。 在这本书本身中,它有冲突的代码。

如果这是我的代码的开始:

import sqlite3

con = sqlite3.connect('stackoverflow.db')

cur = conn.cursor()

要提交,我会使用 con.commit() 还是 cur.commit()。还是有不同的时间使用不同的?

以下是书中的图片:

这显示了 con.commit()

这显示了 cur.commit()

我在https://docs.python.org/3/library/sqlite3.html 在线查看并显示 con.commit()

只是想确定一下这本书是否有使用cur.commit()的错误,或者是否有特殊的使用条件。

提前致谢

【问题讨论】:

  • 你试过代码了吗?你发现了什么?
  • 最佳建议。我是编程新手,所以我总是觉得如果我写错代码会搞砸一些事情':) cur.commit 不起作用。我将发布一个包含详细信息的解决方案。感谢您帮助我了解更多信息:)

标签: python python-3.x sqlite commit


【解决方案1】:

con.commit()conn.commit() 是相同的...它们是创建的对象类型...在这两种情况下它们都以其他方式命名...重要的主要是.commit() 而不是程序员指定的命名

有些对象类型使用不同的名称(con 和 cur - 如您所问)来调用该方法。您还可以在代码中使用不同的名称,例如:

db = sqlite3.connect('/tmp/filename.db')
cursor = db.cursor()
cursor.execute("CREATE TABLE ....
               .... some DB-API 2.0 commands ....
               ")
db.commit()

请再次查看网页https://docs.python.org/3/library/sqlite3.html。 您忘记从网页中复制这两行:

import sqlite3
conn = sqlite3.connect('example.db')

然后继续代码(只是复制它):

c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
conn.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

【讨论】:

【解决方案2】:

我听从了unutbu的建议并亲自尝试了。

示例代码:

import sqlite3

con = sqlite3.connect('db.db')
cur = con.cursor()

data = [('data', 3), ('data2', 69)]

cur.execute('CREATE TABLE Density(Name TEXT, Number INTEGER)')

for i in data:
    cur.execute('INSERT INTO Density VALUES (?, ?)', (i[0], i[1]))

cur.commit()

PyCharm 运行:

Traceback (most recent call last):
  File "/Users/User/Library/Preferences/PyCharmCE2018.1/scratches/scratch_2.py", line 13, in <module>
    cur.commit()
AttributeError: 'sqlite3.Cursor' object has no attribute 'commit'

教科书错误。 cur.commit() 不存在。

感谢 unutbu 和 s3n0

【讨论】:

    【解决方案3】:

    我认为如果您使用指定的游标来提交更改,在您的情况下,它应该是 cur.connection.commit()。 无论是命名为 db、con 还是 conn,您始终可以在代码末尾使用 connect 来提交。 但是当你的代码变得复杂时,你将有不同的函数对数据库进行某些操作,如果你只使用连接提交,当出现错误时,你将很难找到哪个函数失败了。因此,您为特定操作创建特定游标,当失败时,回溯消息将显示错误时哪个特定游标。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 2015-04-20
      • 2014-05-12
      • 1970-01-01
      • 2023-01-18
      相关资源
      最近更新 更多