是这样的,我的项目是
handlers层 → dao层
因为在handler层开了个conn,把conn传到dao层,让dao层去真正处理数据,类似:
@classmethod
@tornado.gen.coroutine
def get_by_order_id(cls, context, conn, order_id):
"""
根据订单号获取订单info
:param context: 上下文环境
:param conn: 数据库连接
:param order_id: 订单id
:return: 订单info
"""
with conn.cursor() as cursor:
sql = "select * from pay where id='%s'" % order_id
yield cursor.execute(sql)
item = cursor.fetchone()
if item:
payinfo = Payinfo(item)
else:
payinfo = None
raise tornado.gen.Return(payinfo)
本来我以为一个connection可以多个cursor的(不然我让我数据库怎么设计?)
一个连接只能有一个cursor?
A connection can have only one cursor with an active query at any time. +If you have used other Python DBAPI databases, this can lead to surprising +results.::
然后问了玮哥,他那边虽然也是一个connection一个cursor,但是可以多个cursor实例。
然后仔细看了下,作者的意思是,一个时间点,只能有一个cursor存活。
千万不要出来这种代码:
c1 = conn.cursor()
c1.execute('SELECT * FROM persons')
c2 = conn.cursor()
c2.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
print( "all persons" )
print( c1.fetchall() ) # shows result from c2 query!
print( "John Doe" )
print( c2.fetchall() ) # shows no results at all!
因为一个时间点不能存活两个cursor。。。
所以可以有如下代码:
c1 = conn.cursor()
c1.execute('SELECT * FROM persons')
print( "all persons" )
print( c1.fetchall() ) # shows result from c2 query!
c2 = conn.cursor()
c2.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
print( "John Doe" )
print( c2.fetchall() ) # shows no results at all!
同步下来,其实每一个时间点只有一个存活的cursor在处理,美滋滋。