pythonmysql连接器和参数化查询

2024-09-27 00:20:49 发布

您现在位置:Python中文网/ 问答频道 /正文

Python 3.6/MySQL5.6

我对python还是相当陌生的,尽管我已经在其他编码语言中使用过MySQL了一段时间。在开发环境中,我希望删除特定数据库中的所有表。我可以删除数据库,但托管提供商锁定了一些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是一个元组;但是,我一直在获取异常和堆栈跟踪:

^{pr2}$

从select result tuple访问表名需要做些什么吗?我是否必须对查询或执行进行不同的排序?是否有一个声明“准备”我失踪了?在


Tags: 代码命令行import脚本数据库closeexecuteos
2条回答

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

An identifier may be quoted or unquoted. If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

...

The identifier quote character is the backtick (`):

您可以这样修改代码:

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

有关MySQL doc的详细信息,请参阅。在

与使用Execute方法填充表名不同,使用基本python字符串原语为DROP语句构造字符串。这样就不会在表名的两边加上引号。(这样会给你一个语法错误。)然后简单地

cursorDrop.execute(query2)

另一个问题:在连接之后和执行删除之前,您需要执行相当于USE db_name的操作。在

相关问题 更多 >

    热门问题