文章内容

2020/9/10 16:00:01,作 者: 黄兵

MySQLdb执行事务

最近有一个需求:将查询出来的数据插入到其他表,之后删除原来表的数据。

这里就涉及到数据库事务的问题:如果插入表失败,那么就不能删除这条数据。

这里就需要使用到数据库事务,下面是Python+MySQLdb的具体实现代码:

get_all = cur.fetchall()
for item in get_all:
    sms_receive_id = item[0]
    phone_number = item[1]
    content = item[2]
    receive_time = item[3]
    is_type = item[4]
    show = item[5]
    phone_number_id = item[6]
    insert_sql = "INSERT INTO history_2019 (PhoneNumber, Content, SMS_ReceiveTime, Type, IsShow, PhoneNumber_id) values (%s,%s,%s,%s,%s,%s)"
    delete_sql = "DELETE FROM table_name WHERE id='{id}';".format(id=sms_receive_id)
    try:
        # 开始执行事务
        # 插入数据
        cur.execute(insert_sql,
                    (phone_number, content, receive_time, is_type, show, phone_number_id))
        # 删除数据
        cur.execute(delete_sql)
        # 提交数据
        mysql_conn.commit()
    except (MySQLdb.Error, MySQLdb.Warning) as e:
        self._logger_write_file.error(
            ' 执行插入和删除SQL命令的时候出现错误,具体错误内容: {error_message}'.format(error_message=e))
        # 发生错误时回滚
        cur.close()
        mysql_conn.rollback()

这里先对查询出来的数据插入到历史表,之后删除本条数据,都成功了提交数据,在try这里没有使用cur.close()的原因参考这篇文章:MySQLdb cursor closed

具体可以参考这篇文章:Python中MySQLdb的事务处理


参考资料:

1、https://www.cnblogs.com/feng18/p/5842196.html

2、MySQLdb cursor closed


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - MySQLdb执行事务

分享到:

发表评论

评论列表