我这样一张Mysql数据表
先前使用Flask写了一个数据处理配置接口,第一次调用该接口传递指定参数,对指定列进行处理返回如下结果
但再次调用该接口处理其他列的时候,返回如下结果
如何返回如下结果?
该接口核心代码大致如下
# 获取数据值
datas = res[0] # ['FOL', 'FOL', 'FOL', 'FOL', 'FOL', 'FOL', 'FOL', 'FOL']
# 获取字段名
col = res[1] # Site
# 查询output_table数据表中存在的字段名
new_field = view_datasheet_field('output_table')
print(new_field)
if col in new_field:
# 执行插入sql语句
sql = f"INSERT INTO output_table ({col}) VALUES (%s)"
# sql = f"UPDATE output_table SET {col}=(%s);"
# 插入数据
for data in datas:
cursor.execute(sql, (data,))
【以下回答由 GPT 生成】
该问题的根本原因是在第一次调用接口时,已经插入了指定列的数值,再次调用接口时没有对已存在的列进行处理。
解决这个问题的方法是,在执行插入前,先检查数据表中是否已存在该列。如果不存在,再执行插入操作;如果存在,可以选择更新已存在的列的值或者直接跳过。
具体的解决方案如下:
def view_datasheet_field(table_name):
# 获取数据表结构信息
cursor.execute(f"DESCRIBE {table_name}")
results = cursor.fetchall()
# 提取字段名
field_names = [r[0] for r in results]
return field_names
# 获取字段名
col = res[1] # Site
# 查询output_table数据表中存在的字段名
new_field = view_datasheet_field('output_table')
# 检查指定列是否已存在
if col not in new_field:
# 执行插入sql语句
sql = f"ALTER TABLE output_table ADD {col} VARCHAR(255)"
cursor.execute(sql)
connection.commit()
print(f"Successfully added new column: {col}")
# 执行插入sql语句
sql = f"INSERT INTO output_table ({col}) VALUES (%s)"
# 插入数据
for data in datas:
cursor.execute(sql, (data,))
这样,无论是否已存在指定列,都可以正常执行插入操作。
【相关推荐】