2017-09-14 53 views
0

我在Python相對較新,但在Java中有更多的經驗,所以我理解了大部分概念。但是,我一直在使用MySQL的問題,並使用MySQL 從函數中傳回信息以便稍後在另一個函數中使用。從功能不工作的Python mysql輸出

我需要使用多個返回字段進行復雜的MySQL查詢,所以我不想爲每個SQL字段運行多個SQL查詢,因爲這會粉碎數據庫。 說下面是我試圖實現的一個小例子。

我想要一個函數來運行SQL查詢(def connectory_mysql()),該函數從別處獲取參數(此部分工作),然後獲取SQL查詢的輸出並傳遞迴主函數以供使用。 然後主函數需要使用不同參數的SQL查詢的不同列結果。

我可以返回結果並將其分配給出現的結果1,並且在打印時看起來像字典,但我無法拆分/使用result1 = connector_mysql中的不同鍵或數據(subSerialNum,ldev,today_date ) 如果我在返回之前在SQL函數中分離字典中的鍵,即ldev_cap = result ['ldev_cap'] 我可以在SQL函數中打印各個元素...但是,我似乎無法傳遞參數,然後返回到主要功能並將它們分離出來?

我一定是錯過了一些東西容易或我不理解的東西...任何幫助或幫助將不勝感激......

...  
result1 = connector_mysql(subSerialNum, ldev, today_date) 

print(result1) #this works and appears to be a dictionary, but I can split it 
       ## into its elements like: 
ldev_cap = result1['ldev_cap'] ##-> this dosn't work here.....???? if i return it as a dictonary.. 
       #and i'm unsure how to split them when i pass just the paramaters 
       #back if i split the dictionary in the sql function. 

... 

def connector_mysql(subSerialNum, ldev, today_date): 

    import pymysql.cursors 

    db_server = 'localhost' 
    db_name = 'CBDB' 
    db_pass = 'secure_password' 
    db_user = 'user1' 

    sql_query = (
     "SELECT ldev_cap, ldev_usdcap FROM Ldevs WHERE sub_serial=%(serial)s " 
     "and ldev_id=%(lun)s and data_date=%(todayD)s") 

    connection = pymysql.connect(host=db_server, 
           user=db_user, 
           password=db_pass, 
           db=db_name, 
           cursorclass=pymysql.cursors.DictCursor) 

    try: 
     with connection.cursor() as cursor: 
      cursor.execute(sql_query, {'serial': subSerialNum, 'lun': ldev, 'todayD': today_date}) 
      result = cursor.fetchone() 

      while result: 
       ldev_cap = result['ldev_cap'] #here the dictionary acts as 
             #expected and i can assign a value 
       ldev_usdcap = result['ldev_usdcap'] 

       print(result) 
       return ldev_cap, ldev_usdcap #here i can return 

    finally: 
     connection.close() 

任何幫助或援助將大大apricated ...

Cheers Graham

回答

0

首先,您應該熟悉用於編寫python代碼的Python style guide

根據您現有的代碼,result1返回包含值爲(ldev_cap, ldef_usdcap)(它不是目錄)的元組。您可以訪問返回結果作爲result1[0],其對應的返回值爲ldev_capresult1[1],其對應的返回值爲ldev_usdcap

或者,因爲你正在返回兩個數據,你可以通過使用

ldev_cap, ldev_usdcap = connector_mysql(subSerialNum, ldev, today_date) 
+0

感謝您的反饋訪問每個返回數據,我明白它不是一個目錄,而是一個字典,是理解元組的概念,我已經嘗試過但沒有工作。 – Graham

+0

也許你應該改說你的問題,你期待從結果中返回什麼?什麼「不起作用」? – hcheung