首页 > 解决方案 > 使用 %s 运算符在 Python 中创建 MySQL 表列

问题描述

类似于使用 %s 运算符在 Python 中创建 MySQL 数据库中的Brunonono (即使使用相同的包),我正在尝试使用 Python 中的 %s 运算符将列从 excel 表添加到 mysql 表。错误是一样的:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s %s)' at line 1

代码如下

mydb=mysql.connector.connect(host="localhost",user="root")

#init cursor
mycursor=mydb.cursor()

column_title="ID"
cell_type="INT(10)"

mycursor.execute("ALTER TABLE Test ADD (%s %s)"),(column_title, cell_type)

可悲的是,我不知道如何应用上面帖子中提供的解决方案,其中

mycursor.execute("CREATE DATABASE (%s)", (db_name))

被替换为

create_statement = "CREATE DATABASE {:s}".format(db_name)
mycursor.execute(create_statement)

标签: pythonmysqlmysql-python

解决方案


mycursor.execute("ALTER TABLE Test ADD (%s %s)"),(column_title, cell_type)是你目前在做什么

相反,

mycursor.execute("ALTER TABLE Test ADD (%s %s)" % (column_title, cell_type))

除非我不正确地了解 MySQL 语法,否则这会起作用


推荐阅读