python 使用定时把源数据库表数据,同步到目标数据库表,并同步前对目标数据库表进行清空操作

import pymysql
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
def get_current_time():
    current_time = datetime.now()
    return current_time






def copy_and_delete_from_tables():
    try:
        #目标数据库
        connection_B = pymysql.connect(host='10.96.21.12', user='root', db='test1',
                     password='123456', port=3306, charset='utf8')
        #源数据库
        connection_A = pymysql.connect(host='10.96.21.13', user='root', db='test2',
                     password='1234567', port=3306, charset='utf8')
        # 创建cursor对象
        cursor_A = connection_A.cursor()
        cursor_B = connection_B.cursor()

        # 查询源数据库
        cursor_A.execute("SELECT * FROM t_bz_test")
        rows = cursor_A.fetchall()
        # 删除目标表t_hj_test数据
        sql2 = "DELETE FROM t_hj_test"
        # 执行SQL删除语句
        cursor_B.execute(sql2)
        print('已删除')
        # 插入到目标数据库目标表
        for row in rows:
            #打印数据行
            #print(row)
            #目标表和源数据表的字段要一一对应不然后插入到其它字段去
            cursor_B.execute("INSERT INTO t_hj_test (id,check_flag,sjly,repeated_id) VALUES (%s,%s,%s,%s)", row)
        # 提交事务
        connection_B.commit()
        print('成功')
    except pymysql.Error as e:
        print(f"Error: {e}")


    finally:
        # 关闭cursor和连接
        cursor_A.close()
        cursor_B.close()
        # connection_A.close()
        # connection_B.close()
                # 在关闭连接之前检查连接状态
        if not connection_A.open:
            print("连接A已经关闭,不再重复关闭。")
        else:
            connection_A.close()

        if not connection_B.open:
            print("连接B已经关闭,不再重复关闭。")
        else:
            connection_B.close()




def my_job():
    # 调用函数并打印当前时间
    start_time = get_current_time()
    print('开始时间:', start_time)
    copy_and_delete_from_tables()
    end_time = get_current_time()  # 获取结束时间
    print('结束时间:', end_time)


scheduler = BackgroundScheduler()
scheduler.add_job(my_job, 'cron', day_of_week='0-6', hour=1, minute=49)  # 每晚1点49执行
scheduler.start()

# 在你的主程序中,通常不需要额外的阻塞操作,因为调度器已经在后台运行了
# 但如果你想要在主程序中做一些其他的事情,并且希望主程序在调度器关闭之前不退出,
# 你可以添加一些逻辑来等待,比如一个等待输入或监听某个事件的循环。

try:
    # 这里可以添加你的其他代码,或者简单地让主线程休眠以避免立即退出
    # 例如,你可以使用time模块的sleep函数来创建一个简单的循环
    import time

    while True:
        time.sleep(2)  # 让主线程休眠2秒,以保持程序运行
except (KeyboardInterrupt, SystemExit):
    # 当接收到Ctrl+C或系统退出时,确保调度器被关闭
    scheduler.shutdown()
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值