bypass known exception of mysql in python

2019-09-12 12:22发布

I am trying to bypass "Cannot delete or update a parent row: a foreign key constraint fails" inside my python script. So I am planning to drop all tables but this error throws up due to inter relationship.

My query is I need to get this automated and i know I am gonna come with the same error, but I know how to bypass it by calling SET FOREIGN_KEY_CHECKS=0; and then once deleted enable the feature again SET FOREIGN_KEY_CHECKS=1;. Need to know how to automate this inside 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()

1条回答
相关推荐>>
2楼-- · 2019-09-12 13:05

I tried the following snip and it worked, thanks anyways.

        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()
查看更多
登录 后发表回答