bypass known exception of mysql in python

风流意气都作罢 提交于 2019-12-12 04:22:53

问题


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:


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()


来源:https://stackoverflow.com/questions/38898601/bypass-known-exception-of-mysql-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!