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
是一个元组;但是,我一直在获取异常和堆栈跟踪:
从select result tuple访问表名需要做些什么吗?我是否必须对查询或执行进行不同的排序?是否有一个声明“准备”我失踪了?在
在MySQL中,schema对象与SQL参数不同,有不同的引号规则,schema对象的引号是反勾(`):
您可以这样修改代码:
有关MySQL doc的详细信息,请参阅。在
与使用
Execute
方法填充表名不同,使用基本python字符串原语为DROP
语句构造字符串。这样就不会在表名的两边加上引号。(这样会给你一个语法错误。)然后简单地另一个问题:在连接之后和执行删除之前,您需要执行相当于
USE db_name
的操作。在相关问题 更多 >
编程相关推荐