2014-11-03 91 views
0

請原諒我,我是相當新的python,我一直在尋找這段的邏輯很長一段時間,但是,不管我嘗試什麼,看起來它總是在打印語句中崩潰。基本上,我只想知道python是否從SQL語句中獲得了正確的值。我甚至試圖做一個 a,b,c = row.split(',')然後print a,但它也出現在打印錯誤。獲取「命令不同步,你現在不能運行這個命令」

with con: 
    cur.execute(query, (next, end,next,end)) 
    print (cur._last_executed) # this prints the correct query. 
    while True: 
     result = cur.fetchmany() 
     if len(result) ==0: 
      break 
     for row in result: 
      myvalues = row.split(',') 
      for value in myvalues: 
       print value # this line is what the traceback says caused it. 

錯誤輸出:

Traceback (most recent call last): 
    File "./export.py", line 55, in <module> 
    print value 
    File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.3-py2.7-linux-x86_64.egg/MySQLdb/connections.py", line 249, in __exit__ 
     self.rollback() 
    _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") 
    Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in <bound method SSCursor.__del__ of <MySQLdb.cursors.SSCursor object at 0x7fc0e0632f10>> ignored 
+0

我猜'row'不是一個字符串,所以'row.split'看起來不對...... – 2014-11-03 19:11:33

+1

回溯清楚地表明,當你調用'self.rollback()',甚至沒有出現錯誤時在你提供的代碼中。而且,如果你沒有顯示你正在運行的命令,你如何期望我們調試你的命令不同步的方式? – 2014-11-03 19:11:41

+0

請顯示完整的回溯 - 從您提供的錯誤信息看,它看起來不像'print value'行是什麼引起了異常。 – martineau 2014-11-03 19:14:29

回答

0

當您退出withconnection.__exit__被調用,而不是在print語句您的錯誤發生。 當你看的MySQLdb的這部分代碼,你會看到:

def __enter__(self): return self.cursor() 

def __exit__(self, exc, value, tb): 
    if exc: 
     self.rollback() 
    else: 
     self.commit() 

所以這立刻告訴我們兩兩件事:

  1. 有前一個例外是由rollback()調用自身原因造成的陰影例外
  2. 你的第一行應該是)with conn as cur:,因爲cur將被賦予connection.__enter__()的結果。

很難說爲什麼你會得到這個錯誤,因爲我們不知道你的光標從哪裏來。你應該改變你的第一行,如上所述,它可能會工作。如果沒有,完全擺脫上下文管理器,您將能夠看到原始異常。

相關問題