MySQL 批量设置主键id自增脚本
SQL server迁移MySQL后自增设置并未迁移至MySQL
批量设置脚本
import pymysql
def dictfetchall(cursor):
# 获取游标描述
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
db = pymysql.connect(host=host, user=user, password=password, database=database)
cursor = db.cursor()
cursor.execute("SHOW TABLES")
data = cursor.fetchall()
tables_list = (i[0] for i in data)
e = []
for i in tables_list:
try:
print(i)
cursor.execute(f"alter table {i} change id id bigint AUTO_INCREMENT;")
except:
e.append(i)
print('==========错误列表==========')
print(e)
print('==========尝试补救==========')
e2 = []
for i in e:
cursor.execute(f"desc {i}")
data = dictfetchall(cursor)
Field = [l['Field'] for l in data]
try:
print(i)
for l in ['id', 'Id', 'ID']:
if l in Field:
cursor.execute(f"ALTER TABLE {i} change {l} {l} int")
cursor.execute(f"ALTER TABLE {i} ADD PRIMARY KEY({l});")
cursor.execute(f"alter table {i} change {l} {l} bigint AUTO_INCREMENT;")
else:
e2.append(i)
except Exception as e:
print(e)
e2.append(i)
print("========设置失败列表========")
print(e2)
db.close()