【需求】在给定条件下,在table中增加一列:先判断 表tab1 中是否存在列col1 ,如果不存在,则在tab1中增加 col1。
【分析】通过一条mysql语句很难实现,alter关键字与where、if等语句不好搭配使用。如果大家有能实现的办法,欢迎指出
【方法】使用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_