在python中绕过mysql的已知异常

2024-04-20 06:57:06 发布

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

我试图绕过python脚本中的“无法删除或更新父行:外键约束失败”。 所以我打算删除所有的表,但是这个错误是由于内部关系引起的。

我的问题是,我需要使这个自动化,我知道我会遇到同样的错误,但我知道如何绕过它,通过调用SET FOREIGN_KEY_CHECKS=0;然后在删除后再次启用该功能SET FOREIGN_KEY_CHECKS=1;。 需要知道如何在python中实现自动化

import MySQLdb
import sys

if len(sys.argv) != 4:
        print "please enter the Hostname to connect followed by:"
        print "mysql username;"
        print "mysql db to connect;"
else:
        _host = sys.argv[1]
        _user = sys.argv[2]
#       _pass = sys.argv[3]
        _db   = sys.argv[3]
        cham = raw_input("please enter the command to be executed:- ")
        _pass = raw_input("please enter password:- ")

        if cham == "drop table":
            db = MySQLdb.connect(host = _host, user = _user,db =  _db, passwd = _pass )
            cursor = db.cursor()
            cursor.execute("show tables")
            for i in cursor.fetchall():
                cursor.execute("drop table" + " " + (i[0]))
                print cursor.fetchall()
                print "all the tables has been deleted"
            db.close()
        else:
            db = MySQLdb.connect(host = _host, user = _user,db =  _db, passwd = _pass )
            cursor = db.cursor()
            cursor.execute(cham)
            print cursor.fetchall()
            db.close()


Tags: thetohostdbconnectsyspasscursor
1条回答
网友
1楼 · 发布于 2024-04-20 06:57:06

我尝试了下面的剪贴,它成功了,无论如何,谢谢。在

        if cham == "drop table":
            db = MySQLdb.connect(host = _host, user = _user,db =  _db, passwd = _pass )
            cursor = db.cursor()
            cursor.execute("show tables")
            for i in cursor.fetchall():
                try:
                    cursor.execute("drop table" + " " + (i[0]))
                    #print cursor.fetchall()
                except:
                    cursor.execute("SET FOREIGN_KEY_CHECKS=0")
                    cursor.execute("drop table" + " " + (i[0]))
                    cursor.execute("SET FOREIGN_KEY_CHECKS=1")
#               print "all the tables has been deleted"
            db.close()

相关问题 更多 >