库表批量新增id字段

实现思路:查询库中的所有表,查询每张表中是否包含id字段,遍历字段结束后如果没有id字段,则新增id

#!/usr/bin/env python3
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pymysql.cursors

"""
功能:为mysql库中每张表增加一个id字段,主键,自增,无符号,非空
"""

dbname = 'test'

connection = pymysql.connect(host='ip', user='deploy', password='deploy@dev', db=dbname, charset='utf8',
                             cursorclass=pymysql.cursors.DictCursor)

results = []

count = []


def query_desc(table_name):
    cursor2 = connection.cursor()
    sql = "select * from " + table_name
    query = cursor2.execute(sql)
    desc = cursor2.description
    number = 0
    for field in desc:
        if field[0] == 'id':
            print(table_name)
            count.append(1)
            break
        else:
            number += 1
    if number == len(desc):
        u_sql = "alter table " + table_name + " add id bigint unsigned not null primary key auto_increment first"
        cursor3 = connection.cursor()
        cursor3.execute(u_sql)


try:
    with connection.cursor() as cursor:
        sql = "SHOW TABLES"
        cursor.execute(sql)
        result = cursor.fetchall()
        for i in range(len(result)):
            results.append(result[i]['Tables_in_test'])
        for a in range(len(results)):
            query_desc(results[a])

finally:
    connection.close()

print(len(count))
print(results)
print(len(results))

 

posted @ 2020-11-14 10:47  华格瑞沙  阅读(157)  评论(0编辑  收藏  举报