【问题标题】:python MySQL connector and parameterized querypython MySQL连接器和参数化查询
【发布时间】: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

要从选择结果元组中访问表名,我需要做些什么特别的事情吗?我是否必须以不同的方式订购查询或执行?是否有我遗漏的“准备”声明?

【问题讨论】:

标签: python mysql


【解决方案1】:

在 MySQL 中,schema 对象与 SQL 参数不同,有不同的引用规则,schema 对象的引号是反引号(`):

标识符可以被引用或不被引用。如果标识符包含特殊字符或者是保留字,则在引用它时必须引用它。 (例外:限定名称中的句点后面的保留字必须是标识符,因此不需要引用。)第 9.3 节“关键字和保留字”中列出了保留字。

...

标识符引号字符是反引号(`):

你可以像这样修改你的代码:

query2 = "DROP TABLE IF EXISTS `%s`" 
...
    cursorDrop.execute(query2 % tableName)

MySQL doc上查看更多信息。

【讨论】:

    【解决方案2】:

    不要使用Execute 填充表名的方法,而是使用基本的python 字符串原语为DROP 语句构造字符串。这样您就不会在表名周围得到额外的引号。 (这会给你一个语法错误。)然后简单地

    cursorDrop.execute(query2)
    

    另一个问题:您需要在连接之后和执行 DROP 之前执行 USE db_name 的等效操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 2015-05-19
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多