Advertisement

python实现在mysql数据表中按条件alter增加一列(字段)

阅读量:

需求

分析

分析

分析

【方法】使用mysql存储过程

【实现】

复制代码
     import pymysql

    
     db = pymysql.connect(host='localhost', user='root', passwd='123123', charset='utf8', port=3306)
    
     cursor = db.cursor()
    
  
    
  
    
 # ----------------------------以下为自定义的mysql存储过程--------------------------------
    
     # 该过程的功能:
    
     # 1,判断table_1中是否有索引列col_1 
    
     # 2,如果没有,则在tabel_1表中创建索引并将其设置为主键,用于专家随机抽取时的索引,然后放到表的第一列
    
  
    
     # 如果之前定义过同名的存储过程,则删除
    
     cursor.execute('drop procedure if exists pro_a;')
    
  
    
     # 定义一个存储过程pro_a,功能是:输入为0时,执行索引创建、设置主键、放置到第一列的操作
    
     cursor.execute('create procedure pro_a(in s int)\
    
     begin\
    
     if (s=0) then\
    
     ALTER TABLE tabel_1 ADD col_1 INT(4) NOT NULL PRIMARY KEY AUTO_INCREMENT FIRST;\
    
     end if;\
    
     end ')
    
  
    
     # 变量赋值,查看tabel_1中是否已存在col_1,不存在则设置col_1_exist为0
    
     cursor.execute('SELECT COUNT(*) into @col_1_exist FROM information_schema.columns WHERE TABLE_NAME="tabel_1" AND COLUMN_NAME="col_1"')
    
  
    
     # 调用之前定义的存储过程
    
     cursor.execute('call pro_a(@col_1_exist)')
    
    
    
    
    代码解读

全部评论 (0)

还没有任何评论哟~