MySQL批量生成复制表SQL语句

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:32   3369   0

目标为每个表生成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();


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP