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

时间:2019-07-04 12:24:46

标签: python mysql mysql-python

类似于Create MySQL Database in Python using the %s operator中的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)

2 个答案:

答案 0 :(得分:0)

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语法,否则这将起作用

答案 1 :(得分:-1)

尝试一下:

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

但这不使用%s运算符。

对不起,这适用于SQLite而非MySQL。