2013-10-10 36 views
1

我有一個數據庫連接方法,它創建連接並將光標設置爲init進程的一部分。Python MySQLdb處理多個遊標:命令不同步

然後我有以下使用遊標方法:

def calculatePercentile(self): 
    user_edits = ur'''SELECT /* SLOW_OK_LIMIT: 1800 */ user_id, user_editcount from user''' 
    num_user_per_percentile = ur'''SELECT /* SLOW_OK_LIMIT: 1800 */ count(user_id) from user where user_editcount = %(count)s'''   
    lang_edit_count_dictionary = {} 
    lang_edit_count_dictionary[self.language] = [] 
    edit_count_list = [] 
    p = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95] 
    bot_users = self._getBotUsers() 
    success = False 
    attempts = 0 
    while attempts < 3 and not success: 
     try: 
      self.dbCursor.execute(user_edits) 
      for user in self.dbCursor.fetchall(): 
       user_id = user['user_id'] 
       user_editcount = user['user_editcount'] 
       if user_id not in bot_users: 
        edit_count_list.append(user_editcount) 
      edit_count_list.sort() 
      for i in p: 
       lang_edit_count_dictionary[self.language].append(np.percentile(edit_count_list, i)) 
      success = True 
     except MySQLdb.OperationalError, sqlEx: 
      attempts += 1 
      if sqlEx[0] == 2006: 
       logging.info("Caught the MySQL server gone away exception") 
       logging.error(sqlEx) 
       time.sleep(10) 
       self.connectServer() 
     except Exception, e: 
      traceback.print_exc() 
      logging.exception(e) 
    for key, values in lang_edit_count_dictionary.iteritems(): 
     print key 
     for value in values: 
      self.dbCursor.execute(num_user_per_percentile, {"count":value}) 
      uEditCount = self.dbCursor.fetchone() 
      print uEditCount 

一下這個方法所做的是,它執行一個查詢獲取數據和轉儲到該數據,然後使用相同的光標來執行另一個查詢內部:

for key, values in lang_edit_count_dictionary.iteritems(): 
    print key 
    for value in values: 
     self.dbCursor.execute(num_user_per_percentile, {"count":value}) 
     uEditCount = self.dbCursor.fetchone() 
     print uEditCount 

什麼情況是,我得到以下錯誤:

self.dbCursor.execute(num_user_per_percentile, {"count":value}) 
    File "/home/auduwage/code/vInterLang/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 201, in execute 
    self.errorhandler(self, exc, value) 
    File "/home/auduwage/code/vInterLang/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler 
    raise errorclass, errorvalue 
_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 SSDictCursor.__del__ of <MySQLdb.cursors.SSDictCursor object at 0x2716ed0>> ignored 

在此之前,我在不同的方法中使用了相同的遊標,我不認爲這與MySql有關,不允許我使用相同的遊標一個接一個地運行多個查詢?還是它? 什麼是解決方案?

回答

3

您無法運行復合sql語句。 你需要將它們分開。

這將返回該錯誤:

cursor.execute("drop database x; drop table y;") 

這將很好地工作:

cursor.execute("drop database x;") 
cursor.execute("drop table y;")