绕过python中mysql的已知异常 [英] bypass known exception of mysql in python

查看:211
本文介绍了绕过python中mysql的已知异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的python脚本中绕过"无法删除或更新父行:外键约束失败". 因此,我计划删除所有表,但是由于相互关系而引发此错误.

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.

我的查询是我需要使此自动化,并且我知道我会遇到相同的错误,但是我知道如何通过调用SET FOREIGN_KEY_CHECKS=0;绕开它,然后一旦删除就再次启用该功能SET FOREIGN_KEY_CHECKS=1;. 需要知道如何在python内部自动化

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

推荐答案

无论如何,我尝试了以下剪裁,但仍有效.

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

这篇关于绕过python中mysql的已知异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆