import os import pymysql path = r'D:\Projects\sql' if not os.path.isdir(path): os.mkdir(path) conn = pymysql.connect(host='192.168.1.17', user='root', passwd="password", db='db1') cur = conn.cursor() cur.execute('''SELECT TABLE_SCHEMA,TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA in('db1') ORDER BY TABLE_SCHEMA,TABLE_NAME''') table_list = cur.fetchall() for table in table_list: sql = 'show create table `{}`.`{}`'.format(table[0], table[1]) print(sql) cur.execute(sql) create_table_list = cur.fetchall() create_table_sql = create_table_list[0][1] create_table_sql = create_table_sql.replace('CREATE TABLE ', 'CREATE TABLE `{}`.'.format(table[0])) #print(create_table_sql) # 每个建表sql保存到一个文件 filepath = os.path.join(path, '{}.{}.sql'.format(table[0], table[1])) with open(filepath, 'w') as rows: print(create_table_sql, file = rows) cur.close() conn.close()