python学习站 /第四周mysql数据库
阅读主题
正文字体
字体大小

19.批量上传

本节1346字2025-04-18 17:11:26
connect = pymysql.connect(
    user='root',
    password='yuting123456',
    host='localhost',
    port=3306,
    charset='utf8mb4',
    database='school'
)
cursor = connect.cursor()

# 创建数据库
try:
    cursor.execute('create database house default character set utf8mb4;')
except pymysql.Error:
    print('数据库存在,直接使用数据库house!')
    cursor.execute('use house;')

# 遍历获取每一个文件
file_names = os.listdir('data')
is_first = True
for fn in file_names:
    f = open(f'data/{fn}', encoding='utf-8')
    r1 = reader(f)
    field_names = next(r1)

    # 创建表
    if is_first:
        field_str = ','.join(f'`{x}` varchar(60)' for x in field_names)
        sql_str = f'create table tb_sh_house(`h_id` int not null unique auto_increment,{field_str},primary key(h_id));'
        try:
            cursor.execute(sql_str)
        except pymysql.Error:
            print('该表已经存在!')
        is_first = False

    # 插入数据
    names = ','.join(field_names)
    format_str = ','.join(['%s' for x in field_names])
    cursor.executemany(f'insert into tb_sh_house({names}) values ({format_str});', list(r1))
    print(f'{fn}中的数据全部上传完成!')

connect.commit()
connect.close()


网友评论

相关作品