乱写的,应该还有更优方案。
def file_row_transfer(table_1, table_2, t_id, t_e, tsfh, cursor, conn):
# table_1 -- 数据表
# table_2 -- 结果表
# t_id -- 主键
# t_e -- 处理字段
# tsfh -- 分隔符
# 3.组装sql语句 需要查询的MySQL语句
sql = f'select {t_id}, {t_e} from {table_1} where {t_e} is not null and length({t_e}) != 0'
sql2 = f'insert into {table_2} ({t_id}, {t_e}) values(%s, %s)'
sql3 = f'create table {table_2} ({t_id} varchar(255), {t_e} text)'
sql4 = f'truncate table {table_2}'
# 执行SQL语句
cursor.execute(sql)
# 获取所有数据
results = cursor.fetchall()
i = 1
while i <= 2:
try:
cursor.execute(sql3)
conn.commit()
i += 1
except:
try:
cursor.execute(sql4)
conn.commit()
for result in results:
v_filed = result[1].split(tsfh)
v_id = result[0]
for v_fileds in v_filed:
cursor.execute(sql2, (v_id, v_fileds))
conn.commit()
except:
print(f'{table_2}已经存在!')
i += 2
i += 2
原表
结果