问:为什么现在 运行 select 不更改时间()

Q: Why not change the time when you run select now()

为什么第二次调用行没有改变显示的日期?要更正 运行 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',)]

离开@jonrsharpe 的评论,我打开了 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.

因此,您的游标会缓存数据,您应该在使用完该游标后调用 close()。据推测,这些游标是轻量级的,如果您的应用程序需要,重新创建其中的许多游标是个不错的主意。

也相关advice求婚

A transaction is started at the first query and it is not closed when the cursor is closed. Probably this makes following queries to be executed in the same snapshot. Try putting the connection in autocommit mode or to issuing a connection.rollback() between each query.

UPD:我尝试添加 conn.set_session(autocommit=True) 它有助于缓存意外结果