批量操作数据库:
class DbConnect:
def __init__(self, db_name):
# 初始化数据库
self.db_name = db_name
self.cursor = None
self.connect = None
def _connect_mysql(self):
"""连接数据库"""
self.connect = pymysql.connect(host="rm-bm*****",
user="press",
db=self.db_name,
password="4v******",
charset='utf8',
# autocommit=True,
cursorclass=pymysql.cursors.DictCursor)
# 使用cursor()方法获取操作游标
self.cursor = self.connect.cursor()
def close_mysql(self):
"""关闭数据库"""
self.cursor.close()
self.connect.close()
def select(self, data):
"""SQL 查询语句"""
self.cursor.execute(data)
results = self.cursor.fetchall()
return results
def execute(self, sql_data, args):
"""SQL 删除、提交、修改语句"""
self._connect_mysql()
try:
# 执行SQL语句
self.cursor.executemany(sql_data, args)
# 提交修改
self.connect.commit()
except BaseException as error:
# 发生错误时回滚
self.connect.rollback()
print(error)
数据库协作数据:
db = DbConnect('workclub')
coll_db = DbConnect('coll_service')
start_work_id = *****
work_sql = []
coll_work = []
coll_work_user = []
# 插入协作作品
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`) " \
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"
# 插入协作作品信息
coll_work_sql = "INSERT INTO `coll_service`.`tbl_collaborate_work` (`work_id`,`work_type`,`author_id`,`work_status`,`del_flag`,`create_time`,`update_time`) " \
"VALUES (%s,%s,%s,%s,%s,%s,%s); "
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`) " \
"VALUES (%s,%s,%s,%s,%s,%s);"
for i in range(1, 500):
work_sql.append((start_work_id + i, 275127340, 1, 1, 0, '新的作品press-' + str(i), '',
'https://dev-cdn',
1, 1, 0, 1626175844, 1626175844))
coll_work.append((start_work_id + i, 1, 275127340, 1, 1, '2021-07-13 16:31:58', '2021-07-13 16:31:58'))
coll_work_user.append((start_work_id + i, 275127340, 1, 1, '2021-07-13 16:31:58', '2021-07-13 16:31:58'))
db.execute(sql, work_sql)
coll_db.execute(coll_work_sql, coll_work)
coll_db.execute(coll_work_user_sql, coll_work_user)
db.close_mysql()
coll_db.close_mysql()