问:为什么不更改运行select now()的时间

2024-06-02 15:44:28 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么行的第二次调用不会更改显示的日期?要更正每次需要重新创建连接时运行select now()?你知道吗

>>> import psycopg2
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2015, 9, 22, 19, 39, 9, 582080)
>>> sql ="""SELECT now();"""
>>> cursor.execute(sql)
>>> rows = cursor.fetchall()
>>> rows
[(datetime.datetime(2015, 9, 22, 19, 39, 31, 397308, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=180, name=None)),)]
>>> datetime.now()
datetime.datetime(2015, 9, 22, 19, 39, 58, 326446)
>>> cursor.execute(sql)
>>> rows = cursor.fetchall()
>>> rows
[(datetime.datetime(2015, 9, 22, 19, 39, 31, 397308, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=180, name=None)),)]
>>> sql ="""SELECT version();"""
>>> cursor.execute(sql)
>>> rows = cursor.fetchall()
>>> rows
[('PostgreSQL 9.1.13 on x86_64-unknown-linux-gnu, compiled by gcc (Debian 4.7.2-5) 4.7.2, 64-bit',)]

Tags: nameimportexecutesqldatetimeselectcursornow
1条回答
网友
1楼 · 发布于 2024-06-02 15:44:28

离开@jornsharpe的评论,我打开了psycopg的文档。从他们的"Best Practices" FAQ

When should I save and re-use a cursor as opposed to creating a new one as needed? Cursors are lightweight objects and creating lots of them should not pose any kind of problem. But note that cursors used to fetch result sets will cache the data and use memory in proportion to the result set size. Our suggestion is to almost always create a new cursor and dispose old ones as soon as the data is not required anymore (call close() on them.) The only exception are tight loops where one usually use the same cursor for a whole bunch of INSERTs or UPDATEs.

因此,您的游标缓存数据,当您处理完该游标时,应该调用^{}。据推测,这些游标是轻量级的,如果您的应用程序需要,重新创建其中的许多游标并不是一个坏主意。你知道吗

相关问题 更多 >