python - 使用 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。提前感谢您的帮助。
解决方案
字符串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))
推荐阅读
- php - 我想通过 PHP/HTML 控制 python 脚本
- swift - 创建一个函数来计算句子中的元音、辅音和标点符号
- zabbix - Zabbix 外部检查从 bash 运行,但不是从管理 Web 控制台中的地图运行
- c# - 如何在有条件的列表中添加不同的值?
- sql - 是否可以在不指定模式的情况下使用 DB2 变量?
- embedded - gpio-key 不在 sys/kernel/debug/gpio 中
- css - 为什么悬停 div 元素在 iOS Safari (iPhone/iPad) 上不起作用?
- git - 当切换回相应的分支时,Git 可以提醒我或自动应用存储吗?
- angular - 如何以角度将模态从一个组件打开到另一个组件?
- java - EclipseLink 如何命名外键?