python串連MySQL小例子

來源:互聯網
上載者:User

建立按天分表的程式:

#!/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 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.