python PyMysql 一个connection里面能不能有多个cursor

是这样的,我的项目是
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在处理,美滋滋。 
Python pymysql一个Python的MySQL数据库驱动程序,它可以让我们方便地使用Python操作MySQL数据库。而事务是指作为一个单独的、不可分割的工作单位执行的一系列操作,只有所有操作都执行成功,才能提交事务;如果任意一个操作失败,就必须回滚事务,撤销已经执行的所有操作。下面介绍一下Python pymysql 中的事务处理。 在 Python pymysql 中,可以使用 connection 对象的 begin() 方法开启一个事务,使用 commit() 方法提交事务,使用 rollback() 方法回滚事务。当开启事务后,在所有的操作中,只有最后执行 commit() 才会将所有的操作提交到数据库中。 例如,下面的代码演示了如何使用 Python pymysql 开启事务、插入数据、更新数据和提交事务: ``` import pymysql # 连接数据库 conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test') try: # 开启事务 conn.begin() # 插入数据 cursor = conn.cursor() cursor.execute("INSERT INTO student (name, age) VALUES ('Tom', 18)") # 更新数据 cursor.execute("UPDATE student SET age = 20 WHERE name = 'Tom'") # 提交事务 conn.commit() except Exception as e: # 回滚事务 conn.rollback() finally: # 关闭连接 conn.close() ``` 在上面的代码中,我们使用了 try...except...finally 来处理异常和关闭连接,使用 conn.begin() 开启事务,使用 conn.commit() 提交事务,使用 conn.rollback() 回滚事务。注意,如果在执行过程中出现了异常,就会跳转到 except 语句块,执行回滚操作,撤销已经执行的所有操作。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值