英文:
I am using PyMongo. Do I have to close a MongoClient after use?
问题
A. 关于游标(cursor),我是否需要手动关闭它?我想知道这一点,因为我真的希望像这样做。
for s in collection.find():
print(s)
B. 关于 MongoClient,我是否需要手动关闭它?这会影响 PyMongo 的连接池功能吗?
from pymongo import MongoClient
url = 'mongodb://localhost:27017'
client = MongoClient(url)
db = client['test']
collection = db['students']
# 查询
cursor = collection.find()
for s in cursor:
print(s)
cursor.close() # 这是否需要?
client.close() # 这是否需要?
我不确定是否有任何区别。
英文:
I am using PyMongo, and I have some questions about connection and cursor.
A. Do I have to close a cursor? I want to know because I really want to do something like this.
for s in collection.find():
print(s)
B. Do I have to close a MongoClient manually? Will it affect the connection polling feature of PyMongo?
from pymongo import MongoClient
url = 'mongodb://localhost:27017'
client = MongoClient(url)
db = client['test']
collection = db['students']
# QUERY
cursor = collection.find()
for s in cursor:
print(s)
cursor.close() # Is this required?
client.close() # Is this required?
I am not sure if there are any differences.
答案1
得分: 1
如文档中所示,cursor.close()
释放了为该游标分配的资源。但是,服务器将在一段时间后自动执行此操作,这并不是(完全)必要的。
如此帖子中所示,关闭游标可能是一个好的实践。
如此帖子中建议最好重用连接而不关闭客户端。
英文:
As shown in the documentation
cursor.close()
frees allocated resources to that cursor. However, the server will automatically do this after a time period, and it is not (entirely) needed.
As shown in this post it is probably good practice to close cursors.
As shown in this post it would be best to reuse connections and to not close the client.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论