【问题标题】:Create MySQL Table Column in Python using the %s operator使用 %s 运算符在 Python 中创建 MySQL 表列
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    但这不使用 %s 运算符。

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

    【讨论】:

    • 这不能回答问题。
    • 这给出了错误:mysql.connector.errors.ProgrammingError: SQL 语句中没有使用所有参数。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2013-07-24
    相关资源
    最近更新 更多