批量操作数据库:

    1. class DbConnect:
    2. def __init__(self, db_name):
    3. # 初始化数据库
    4. self.db_name = db_name
    5. self.cursor = None
    6. self.connect = None
    7. def _connect_mysql(self):
    8. """连接数据库"""
    9. self.connect = pymysql.connect(host="rm-bm*****",
    10. user="press",
    11. db=self.db_name,
    12. password="4v******",
    13. charset='utf8',
    14. # autocommit=True,
    15. cursorclass=pymysql.cursors.DictCursor)
    16. # 使用cursor()方法获取操作游标
    17. self.cursor = self.connect.cursor()
    18. def close_mysql(self):
    19. """关闭数据库"""
    20. self.cursor.close()
    21. self.connect.close()
    22. def select(self, data):
    23. """SQL 查询语句"""
    24. self.cursor.execute(data)
    25. results = self.cursor.fetchall()
    26. return results
    27. def execute(self, sql_data, args):
    28. """SQL 删除、提交、修改语句"""
    29. self._connect_mysql()
    30. try:
    31. # 执行SQL语句
    32. self.cursor.executemany(sql_data, args)
    33. # 提交修改
    34. self.connect.commit()
    35. except BaseException as error:
    36. # 发生错误时回滚
    37. self.connect.rollback()
    38. print(error)

    数据库协作数据:

    1. db = DbConnect('workclub')
    2. coll_db = DbConnect('coll_service')
    3. start_work_id = *****
    4. work_sql = []
    5. coll_work = []
    6. coll_work_user = []
    7. # 插入协作作品
    8. sql = "INSERT INTO `ide_work` (`id`,`user_id`,`type`,`status`,`hidden_flag`,`name`,`cover_url`,`preview_url`,`ide_type`,`stage_type`,`published_at`,`updated_at`,`created_at`) " \
    9. "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"
    10. # 插入协作作品信息
    11. coll_work_sql = "INSERT INTO `coll_service`.`tbl_collaborate_work` (`work_id`,`work_type`,`author_id`,`work_status`,`del_flag`,`create_time`,`update_time`) " \
    12. "VALUES (%s,%s,%s,%s,%s,%s,%s); "
    13. coll_work_user_sql = "INSERT INTO `coll_service`.`tbl_collaborate_work_user` (`work_id`,`coll_user_id`,`work_type`,`del_flag`,`create_time`,`update_time`) " \
    14. "VALUES (%s,%s,%s,%s,%s,%s);"
    15. for i in range(1, 500):
    16. work_sql.append((start_work_id + i, 275127340, 1, 1, 0, '新的作品press-' + str(i), '',
    17. 'https://dev-cdn',
    18. 1, 1, 0, 1626175844, 1626175844))
    19. coll_work.append((start_work_id + i, 1, 275127340, 1, 1, '2021-07-13 16:31:58', '2021-07-13 16:31:58'))
    20. coll_work_user.append((start_work_id + i, 275127340, 1, 1, '2021-07-13 16:31:58', '2021-07-13 16:31:58'))
    21. db.execute(sql, work_sql)
    22. coll_db.execute(coll_work_sql, coll_work)
    23. coll_db.execute(coll_work_user_sql, coll_work_user)
    24. db.close_mysql()
    25. coll_db.close_mysql()