python MySQL连接器和参数化查询

7片芦苇

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

要从选择结果元组访问表名,我需要做些特别的事情吗?我是否必须对查询进行排序或执行方式有所不同?是否有我准备中的“准备”声明?

georgexsh

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

标识符可以带引号或不带引号。如果标识符包含特殊字符或为保留字,则在引用标识符时必须将其引用。(例外:限定名称后的保留字必须是标识符,因此不必加引号。)保留字在第9.3节“关键字和保留字”中列出。

...

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

您可以这样修改代码:

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

查看更多有关MySQL文档的信息

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章