python 字符串以逗号隔开拆分成多列(小白到废物)

乱写的,应该还有更优方案。

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

原表

 

  结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值