python批量修改数据库字段类型


#首先这个代码没有提取不够简练

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymysql
import datetime
import time
import re,string

host = "19.206.25.24"
mysql_user_name = "root"

now = datetime.datetime.now()
now_timestamp = int(time.time())

def update_create_time_type():
    row_list = find_create_time_row()
    db = pymysql.connect(host=host, user=mysql_user_name, password="123456789", database="waresic")
    cursor = db.cursor()
    for row in row_list:
        msg = str(row)
        msg = msg.replace(',', '')
        newmsg = msg.replace('\'', '')
        newmsg = newmsg[1:]
        newmsg=newmsg.strip(')')
        print (newmsg+'\n')
        cursor.execute(newmsg)
    db.commit()
    db.close()
    return 

# `create_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间',
#   `update_at`  COMMENT '更新时间',


def find_create_time_row():
    sql = "select CONCAT('ALTER TABLE  ',TABLE_NAME,'  MODIFY  ', COLUMN_NAME, ' datetime(3) NOT NULL DEFAULT current_timestamp(3);') from information_schema.COLUMNS where TABLE_SCHEMA = 'waresic' and  COLUMN_NAME = 'create_time';"
    db = pymysql.connect(host=host, user=mysql_user_name, password="123456789", database="information_schema")
    cursor = db.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    db.commit()
    db.close()
    return rows


def update_time_exe():
    zone_list = find_update_time_rows()
    db = pymysql.connect(host=host, user=mysql_user_name, password="123456789", database="waresic")
    cursor = db.cursor()
    for row in zone_list:
        msg = str(row)
        msg = msg.replace(',', '')
        newmsg = msg.replace('\'', '')
        newmsg = newmsg[1:]
        newmsg=newmsg.strip(')')
        print (newmsg+'\n')
        cursor.execute(newmsg)
    db.commit()
    db.close()
    return 


def find_update_time_rows():
    sql = "select CONCAT('ALTER TABLE  ',TABLE_NAME,'  MODIFY  ', COLUMN_NAME, ' datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) ;') from information_schema.COLUMNS where TABLE_SCHEMA = 'waresic' and  COLUMN_NAME = 'update_time';"
    db = pymysql.connect(host=host, user=mysql_user_name, password="123456789", database="information_schema")
    cursor = db.cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    db.commit()
    db.close()
    return rows



def main():
    update_time_exe()
    update_create_time_type()
    return

if __name__ == '__main__':
    main()

一分钟发个博

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值