建立按天分表的程式:
#!/usr/bin/python2.6# -*- coding: utf-8 -*- import datetime#import MySQLdb tbname="alter table tip"ddl="""add index idx_timestamp(timestamp,appid,appcallcount);""" #dbuser="root"#dbpass=""#dbname="test"#socket="/home/mysql/run/mysql.sock" file_hd=open("alter.sql","w+")#try:# db=MySQLdb.connect(user=dbuser,passwd=dbpass,db=dbname,unix_socket=socket,charset="gbk")# c=db.cursor()#except MySQLdb.Error,e:# print "connection failed!Error %d:%s"%(e.args[0],e.args[1])#def is_leap_year(year): if (year%4==0) and (year%100!=0): return True elif year%400==0: return True else: return False mm31_list=(1,3,5,7,8,10,12)# 31 daysmm30_list=(4,6,9,11) # 30daysddl_buffer=""i=1j=1m=1n=1while i<=12: if i in mm31_list: while j<=31: # print "alter table %s_%02d_%02d %s"%(tbname,i,j,ddl) ddl_buffer=ddl_buffer+"%s_%02d_%02d %s"%(tbname,i,j,ddl) j=j+1 j=1# try:# c.execute(ddl_buffer)# except MySQLdb.Error,e:# print "Error %d: %s\nfailed\n%s\n" % (e.args[0], e.args[1], ddl_buffer) file_hd.write(ddl_buffer) ddl_buffer="" elif i in mm30_list: while m<=30: ddl_buffer=ddl_buffer+"%s_%02d_%02d %s"%(tbname,i,m,ddl) m=m+1 m=1# try:# c.execute(ddl_buffer)# except MySQLdb.Error,e:# print "Error %d: %s\nfailed\n%d\n" % (e.args[0], e.args[1], i) file_hd.write(ddl_buffer) ddl_buffer="" elif i==2: while n<=29: ddl_buffer=ddl_buffer+"%s_%02d_%02d %s"%(tbname,i,n,ddl) n=n+1 n=1# try:# c.execute(ddl_buffer)# except MySQLdb.Error,e:# print "Error %d: %s\nfailed\n%d\n" % (e.args[0], e.args[1], i) file_hd.write(ddl_buffer) ddl_buffer="" i=i+1#db.commit()#db.close()file_hd.close()
參考資料:http://mysql-python.sourceforge.net/MySQLdb.html