• python连接MySQL小例子


    创建按天分表的程序:

    #!/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 days
    mm30_list=(4,6,9,11) # 30days
    ddl_buffer=""
    i=1
    j=1
    m=1
    n=1
    while 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 

  • 相关阅读:
    controller传到页面的值出现乱码
    Uncaught SyntaxError: Unexpected identifier
    No mapping found for HTTP request with URI xxx/resources/js/jquery.min.js...
    jQuery,Ajax和json
    idea中tomcat启动但是访问不了localhost:8080页面
    不允许有匹配 "[xX][mM][lL]" 的处理指令目标。
    11.流程控制之if判断
    10.可变,不可变数据类型
    Python基础
    文件处理
  • 原文地址:https://www.cnblogs.com/sunss/p/2610618.html
Copyright © 2020-2023  润新知