我对事务数据库有些陌生,并且遇到了我试图理解的问题。
我创建了一个简单的演示,其中一个数据库连接存储在cherrypy 创建的5 个线程中的每一个中。我有一个方法可以显示存储在数据库中的时间戳表和一个按钮来添加新的时间戳记录。
该表有 2 个字段,一个用于 python 传递的 datetime.datetime.now() 时间戳,另一个用于设置为默认 NOW() 的数据库时间戳。
CREATE TABLE test (given_time timestamp,
default_time timestamp DEFAULT NOW());
我有两种与数据库交互的方法。第一个将创建一个新游标,插入一个新的 given_timestamp,提交游标,并返回到索引页面。第二种方法将创建一个新游标,选择 10 个最近的时间戳并将其返回给调用者。
import sys
import datetime
import psycopg2
import cherrypy
def connect(thread_index):
# Create a connection and store it in the current thread
cherrypy.thread_data.db = psycopg2.connect('dbname=timestamps')
# Tell CherryPy to call "connect" for each thread, when it starts up
cherrypy.engine.subscribe('start_thread', connect)
class Root:
@cherrypy.expose
def index(self):
html = []
html.append("<html><body>")
html.append("<table border=1><thead>")
html.append("<tr><td>Given Time</td><td>Default Time</td></tr>")
html.append("</thead><tbody>")
for given, default in self.get_timestamps():
html.append("<tr><td>%s<td>%s" % (given, default))
html.append("</tbody>")
html.append("</table>")
html.append("<form action='add_timestamp' method='post'>")
html.append("<input type='submit' value='Add Timestamp'/>")
html.append("</form>")
html.append("</body></html>")
return "\n".join(html)
@cherrypy.expose
def add_timestamp(self):
c = cherrypy.thread_data.db.cursor()
now = datetime.datetime.now()
c.execute("insert into test (given_time) values ('%s')" % now)
c.connection.commit()
c.close()
raise cherrypy.HTTPRedirect('/')
def get_timestamps(self):
c = cherrypy.thread_data.db.cursor()
c.execute("select * from test order by given_time desc limit 10")
records = c.fetchall()
c.close()
return records
if __name__ == '__main__':
cherrypy.config.update({'server.socket_host': '0.0.0.0',
'server.socket_port': 8081,
'server.thread_pool': 5,
'tools.log_headers.on': False,
})
cherrypy.quickstart(Root())
我希望 given_time 和 default_time 时间戳彼此之间只有几微秒的差距。但是我得到了一些奇怪的行为。如果我每隔几秒添加一次时间戳,则 default_time 不会与 given_time 相差几微秒,但通常与前一个given_time 相差几微秒。
给定时间 默认时间 2009-03-18 09:31:30.725017 2009-03-18 09:31:25.218871 2009-03-18 09:31:25.198022 2009-03-18 09:31:17.642010 2009-03-18 09:31:17.622439 2009-03-18 09:31:08.266720 2009-03-18 09:31:08.246084 2009-03-18 09:31:01.970120 2009-03-18 09:31:01.950780 2009-03-18 09:30:53.571090 2009-03-18 09:30:53.550952 2009-03-18 09:30:47.260795 2009-03-18 09:30:47.239150 2009-03-18 09:30:41.177318 2009-03-18 09:30:41.151950 2009-03-18 09:30:36.005037 2009-03-18 09:30:35.983541 2009-03-18 09:30:31.666679 2009-03-18 09:30:31.649717 2009-03-18 09:30:28.319693
然而,如果我大约每分钟添加一个新的时间戳,那么 given_time 和 default_time 都只有几微秒,正如预期的那样。但是,在提交第 6 个时间戳(线程数 + 1)之后,default_time 与第一个 given_time 时间戳相差几微秒。
给定时间 默认时间 2009-03-18 09:38:15.906788 2009-03-18 09:33:58.839075 2009-03-18 09:37:19.520227 2009-03-18 09:37:19.520293 2009-03-18 09:36:04.744987 2009-03-18 09:36:04.745039 2009-03-18 09:35:05.958962 2009-03-18 09:35:05.959053 2009-03-18 09:34:10.961227 2009-03-18 09:34:10.961298 2009-03-18 09:33:58.822138 2009-03-18 09:33:55.423485
即使我在每次使用后都明确关闭游标,但似乎前一个游标仍在被重用。如果我在完成后关闭光标并每次创建一个新光标,这怎么可能?有人可以解释一下这里发生了什么吗?
更接近答案:
我在 get_timestamps 方法中添加了 cursor.connection.commit() ,现在它为我提供了带有时间戳的准确数据。谁能解释为什么我需要调用 cursor.connection.commit() 当我所做的只是一个选择?我猜每次我得到一个游标时,一个事务就会开始(或继续使用它提交的现有事务单元)。有没有更好的方法来做到这一点,或者我每次得到一个光标时都会坚持提交,不管我用那个光标做什么?