使用 %s 运算符在 Python 中创建 MySQL Table 列

Create MySQL Table Column in Python using the %s operator

类似于 中的 Brunonono(即使使用相同的包)我正在尝试将 excel table 中的列添加到 mysql table 在 Python 中使用 %s 运算符。错误是一样的:

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)

遗憾的是,我不知道如何应用上面 post 中提供的解决方案,其中

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

被替换为

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

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 正确的语法,否则这会起作用

试试这个:

mycursor.execute('ALTER TABLE Test ADD (?, ?)',(column_title,cell_type))

但这不使用 %s 运算符。

抱歉,这适用于 SQLite 而不是 MySQL。