【发布时间】:2018-04-23 00:26:16
【问题描述】:
Python 3.6 / MySQL 5.6
虽然我在其他编码语言中使用 MySQL 有一段时间了,但我对 python 还是很陌生。在开发环境中,我想删除特定数据库中的所有表。我可以删除数据库,但托管服务提供商锁定了一些 MySQL 控件,因此可以从命令行或代码中删除“数据库”,但只能通过其管理 Web 面板创建它们。那是一种耗时的痛苦。我可以更轻松地从命令行或代码中删除/创建表。
我编写了一个 python 脚本,当我想清理/重新启动项目时,我可以从 Makefile 调用它。
import os
import mysql.connector.django
DBI = mysql.connector.connect(
option_files=os.path.join(os.path.expanduser("~"), ".my.cnf"),
option_groups="membersdev"
)
cursorFind = DBI.cursor(buffered=True)
cursorDrop = DBI.cursor(buffered=True)
query = """
select TABLE_NAME
from information_schema.TABLES
where TABLE_SCHEMA = %s
"""
cursorFind.execute(query, ('dev_site_org',))
query2 = "DROP TABLE IF EXISTS %s"
for tableName in cursorFind.fetchall():
cursorDrop.execute(query2, tableName)
cursorDrop.close()
cursorFind.close()
DBI.close()
我很确定“query2”在语法上是正确的一个参数。我认为cursorDrop.execute(query2, tableName) 是正确的,因为tableName 是一个元组;但是,我不断收到异常和堆栈跟踪:
Traceback (most recent call last):
File "/home/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 377, in cmd_query
raw_as_string=raw_as_string)
_mysql_connector.MySQLInterfaceError: 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 ''My_First_Table'' at line 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "misc_scripts/db_delete.py", line 35, in <module>
cursorDrop.execute(query2)
File "/home/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/mysql/connector/cursor_cext.py", line 264, in execute
raw_as_string=self._raw_as_string)
File "/home/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 380, in cmd_query
sqlstate=exc.sqlstate)
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 ''My_First_Table'' at line 1
要从选择结果元组中访问表名,我需要做些什么特别的事情吗?我是否必须以不同的方式订购查询或执行?是否有我遗漏的“准备”声明?
【问题讨论】:
-
你能不能试试
cursorDrop.execute(query2, tableName[1:-1]),那双'真的很奇怪。