【发布时间】:2019-07-04 12:24:46
【问题描述】:
类似于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)
【问题讨论】:
-
用
(db_name,)替换(db_name) -
在 Python 交互式 shell 中使用“格式”来感受它的工作原理。当然还要阅读文档。
-
带有 db_name 的部分正在引用另一篇文章。这实际上不是我的问题的一部分。我的错误发生在 mycursor.execute("ALTER TABLE Test ADD (%s %s)"),(column_title, cell_type)
-
@MichaelButscher 我认为这意味着我的问题同样可以使用这种方法解决? :) 太好了
-
您不能使用查询参数替换列名、表名或类型等文字。您必须为此使用字符串格式。见here。
标签: python mysql mysql-python