使用最新版PyCharm操作MySQL为salesperson表新增列报错如何解决
用mysql.connector为MySQL表新增列的报错修正
核心报错原因
- 预定义的ALTER TABLE语句未做字符串替换:代码中写的
command = "alter table salesperson add {name} {data}"为固定字符串,既没有通过格式化方法把用户输入的列名、数据类型填充到SQL中,执行时MySQL会直接把{name}识别为非法列名,触发语法错误 - 变量定义顺序颠倒:先定义了SQL模板字符串,之后才通过
input()获取用户输入的列名和数据类型,即使后续做字符串格式化也无法获取到对应变量值 - 执行顺序逻辑错误:执行ALTER语句后没有立刻提交事务,反而先执行SELECT查询拉取表数据、再调用
commit(),导致查询时拿不到刚新增的列结构
修正后的可运行代码
import mysql.connector mycon = mysql.connector.connect( host='localhost', user='root', passwd='paswd', database='11b' ) if mycon.is_connected(): print('Connection established successfully.') else: print('Connection not established.') exit() mycursor = mycon.cursor() # 先获取用户输入,再拼接可执行的SQL语句 name = input("Enter the name of column you want to add:") data = input("Enter the data type of the column:") command = f"ALTER TABLE salesperson ADD {name} {data}" # 执行新增列操作并立刻提交,保证元数据变更生效 mycursor.execute(command) mycon.commit() # 提交完成后再查询表数据 query = "SELECT * FROM salesperson" mycursor.execute(query) result = mycursor.fetchall() for row in result: print(row) # 资源释放 mycursor.close() mycon.close()
注意:mysql.connector的参数化查询仅支持DML语句中的值占位,不支持列名、表名、数据类型这类数据库对象标识的占位,如果工具会接收外部用户输入,需要对输入的列名、数据类型做白名单校验,避免SQL注入风险。
内容的提问来源于stack exchange,提问作者mindofVISHESH
相关产品推荐
相关产品推荐

