2016-08-11 40 views
0

我試圖繞過「無法刪除或更新父行:外鍵約束失敗」在我的python腳本中。 所以我打算刪除所有的表,但由於相互關係,這個錯誤會拋出。繞過python中已知的mysql異常

我的查詢是我需要得到這個自動化,我知道我會來與相同的錯誤,但我知道如何繞過它通過調用SET FOREIGN_KEY_CHECKS=0;,然後一旦刪除啓用功能再次SET FOREIGN_KEY_CHECKS=1;。 需要知道如何實現自動化這裏面蟒蛇

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

回答

0

我嘗試以下剪斷和它的工作,感謝反正。

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