MySQL批量生成复制表SQL语句

目标为每个表生成0-X个后缀,便于在做一些分表存储时表创建,

python脚本如下:

#!/usr/bin/python
# Author: pecywang
# 2013-05-21

import MySQLdb

TABLES = ("t_a_", "t_b_");

conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='pwd', db='my_db', port=9005);

if(not conn):
    print "Can't connect with mysql!";
    exit();

cur = conn.cursor();

f = file('sql.txt', 'w');
for t in TABLES:
    #print "t:", t;
    cur.execute('show create table %s'%(t));
    res = cur.fetchall();
    sql = res[0][1];
    for i in range(16):
        table_name = "%s%d"%(t, i);
        #print table_name;
        f.write('DROP TABLE IF EXISTS %s;\n'%(table_name));
        new_sql = sql.replace(t, table_name);
        f.write('%s;\n'%(new_sql));

f.close();
cur.close();
conn.close();


 

你可能感兴趣的:(总结沉淀)