利用python批量修改MySQL表结构

1,328 阅读1分钟

前些天开发给了100多张表,要把表中的某一个字段类型修改一下。当时稍微有点懵。紧接着就发现这些需要修改的表其实都是有共性的,就是使用同一个模板可以修改所有的表。下面是具体的代码实现。#掘金·Python 月

#!/usr/bin/env python
#coding=utf-8
import MySQLdb as mysql
import sys

#打开数据库连接
mydb = mysql.connect(host="127.0.0.1",
                     user="guoew",
                     passwd="guoew",
                     db="guoew")

#使用cursor()方法获取操作游标 
cur = mydb.cursor()
#执行sql操作语句
statement = """SHOW TABLES"""
command = cur.execute(statement)
results = cur.fetchall()

#列出当前数据库下的表,将表存储到tables_list列表中.
tables_list = []
for record in results:
        tables_list.append(record[0])

#循环列表,找到符合要求的表明,将其改之
for i in range(len(tables_list)):
    statement = """DESCRIBE %s""" %tables_list[i]
    command = cur.execute(statement)
    results = cur.fetchall()
    for record in results:
        if record[0] == 'id' and record[1] == 'int(11)':
            print "%s in %s" %(record[0],tables_list[i])
            statement = """alter table %s modify column id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增id'""" %tables_list[i]
            command = cur.execute(statement)
            colume_list.append(record[0])
            
#提交并退出
mydb.commit()
mydb.close()