在SQLite中关闭游标或连接之间有什么区别吗? [英] Is there any difference between closing a cursor or a connection in SQLite?

查看:213
本文介绍了在SQLite中关闭游标或连接之间有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦完成数据库操作,我就一直使用命令 cur.close()

I have been using always the command cur.close() once I'm done with the database:

import sqlite3

conn = sqlite3.connect('mydb')
cur = conn.cursor()
# whatever actions in the database
cur.close()

但是,在某些情况下,我只是看到以下内容方法:

However, I just saw in some cases the following approach:

import sqlite3

conn = sqlite3.connect('mydb')
cur = conn.cursor()
# whatever actions in the database
cur.close()
conn.close()

,并在官方文档有时光标是关闭的,有时是连接的,有时是两者。

And in the official documentation sometimes the cursor is closed, sometimes the connection and sometimes both.

我的问题是:


  1. cur.close() conn.close()有什么区别吗?

  2. 完成后是否足以关闭一个(或者必须关闭b其他)?如果是这样,哪个更可取?

  1. Is there any difference between cur.close() and conn.close()?
  2. Is it enough to close one, once I am done (or I must close both)? If so, which one is preferable?


推荐答案

[在关闭游标上]

如果关闭游标,则只是将其标记为无效,无法处理其他请求(我已经完成了)。

If you close the cursor, you are simply flagging it as invalid to process further requests ("I am done with this").

因此,在函数/事务末尾,您应继续关闭游标,以提示数据库该事务已完成。

So, in the end of a function/transaction, you should keep closing the cursor, giving hint to the database that that transaction is finished.

一个好的模式是使游标短暂存在:从连接对象中获得一个游标,执行所需的操作,然后将其丢弃。因此,关闭很有意义,您应该在使用它的代码部分的末尾继续使用 cursor.close()

A good pattern is to make cursors are short-lived: you get one from the connection object, do what you need, and then discard it. So closing makes sense and you should keep using cursor.close() at the end of your code section that makes use of it.

相信(找不到任何引用),如果只是让光标超出范围(功能结束,或者只是 del光标),您应该会得到相同的行为。但是为了良好的编码习惯,您应该明确将其关闭。

I believe (couldn't find any references) that if you just let the cursor fall out of scope (end of function, or simply del cursor) you should get the same behavior. But for the sake of good coding practices you should explicitly close it.

[连接对象]

当实际上完成了数据库的 时,应关闭与其的连接。这意味着 connection.close()

When you are actually done with the database, you should close your connection to it. that means connection.close()

这篇关于在SQLite中关闭游标或连接之间有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆