首页 > 解决方案 > 使用 Python 向 MySQL 中的表添加新列时出错

问题描述

一般来说,我是 MySQL 和数据库的新手,但是当我尝试在表中添加一个新的整数列时遇到了一些问题。要添加一个新列,我这样做:

import mysql.connector

mydb = mysql.connector.connect(
    # host, user, password and database
)

mycursor = mydb.cursor(buffered = True)

# some stuff to get the variable domain

mycursor.execute('ALTER TABLE domainsMoreUsed ADD {} INTEGER(10)'.format(domain)) # domain is a string

但我收到此错误:

raise errors.get_mysql_exception(exc.errno, msg=exc.msg,
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 'in INTEGER(10)' at line 1

我在上面也遇到了同样的错误:

mycursor.execute('ALTER TABLE domainsMoreUsed ADD %s INTEGER(10)' % domain)

相反,当我使用:

mycursor.execute('ALTER TABLE domainsMoreUsed ADD %s INTEGER(10)', (domain))

我得到:

raise ValueError("Could not process parameters")
ValueError: Could not process parameters

我阅读了其他用户关于相同错误的一些帖子,但我找不到我需要的东西。我很确定 SQL 语法是正确的。我在 Windows 10 上使用 MySQL 8.0 和 Python 3.8.3。提前感谢您的帮助。

标签: pythonmysqldatabase

解决方案


字符串domain设置为什么?错误消息syntax to use near 'in INTEGER(10)' at line 1暗示“in”,这是一个保留字。如果要将其用于表或列名称,则需要在它们周围添加反引号:“`”(键盘顶行的“1”左侧)。

像这样更改您的查询:

mycursor.execute('ALTER TABLE domainsMoreUsed ADD `{}` INTEGER(10)'.format(domain))

mycursor.execute('ALTER TABLE domainsMoreUsed ADD `%s` INTEGER(10)', (domain))

推荐阅读