python更新mysql两种方式

方式一:

import pymysql

'''
【数据清理】执行时间超过当前24小时,设置执行状态为失败
流程执行记录表-auto_workflow_exec_records
'''

# 连接数据库
connection = pymysql.connect(host="127.0.0.1", user="root", password="123456",
							 database="merak", port=3306, charset='utf8',
                             cursorclass=pymysql.cursors.DictCursor)


# 更新
def update():
    try:
        '''with语法:
        	会依次执行当前connection类 __enter__(self)、connect(self,...)、
        	__exit__(self, *exc_info),而__exit__方法包括self.close()方法
        '''
        with connection:
            with connection.cursor() as cursor:
                sql = """
                    update auto_workflow_exec_records set execute_state = 0
                    where `execute_state` = 2 
                    and HOUR(TIMEDIFF(NOW(),`create_time`)) > 24 
                    ORDER BY `create_time` desc;
                """
                # 执行创建sql语句
                cursor.execute(sql)
            # 提交数据
            connection.commit()
        '''with语法会关闭connection,或再执行connection.close(),会报:
           pymysql.err.Error: Already closed
        '''
        #connection.close()
    except pymysql.err.MySQLError as _error:
        print(_error)
        raise _error


if __name__ == "__main__":
    update()

方式二:

import time
import pymysql

'''
【数据清理】执行时间超过当前24小时,设置执行状态为失败
流程执行记录表-auto_workflow_exec_records
'''
# 连接数据库
def get_conn():
    _connection = pymysql.connect(host="127.0.0.1", user="root", password="1q2w3e4r",
                                  database="merak", port=3306, charset='utf8',
                                  cursorclass=pymysql.cursors.DictCursor)
    _cursor = _connection.cursor()
    return _connection, _cursor


# 更新
def update(connection, cursor):
    try:
        sql = """
            update auto_workflow_exec_records set execute_state = 2
            where `execute_state` = 0 and HOUR(TIMEDIFF(NOW(),`create_time`)) > 24 
            ORDER BY 	`create_time` desc;
        """
        # 执行创建sql语句
        cursor.execute(sql)
        # 提交数据
        connection.commit()
    except pymysql.err.MySQLError as _error:
        print(f'_error:{_error}')
        raise _error


def close_conn(connection, cursor):
    if cursor:
        cursor.close()
    if connection:
        connection.close()


if __name__ == "__main__":
    connection, cursor = get_conn()
    try:
        update(connection, cursor)
    except pymysql.err.MySQLError:
        print('catch MySQLError')
    close_conn(connection, cursor)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值