2015-07-05 29 views
2

我在主函數中打開mysql連接,並在主函數調用的多個函數中使用該連接。Python,在多個函數中共享mysql連接 - 傳遞連接或遊標?

從主函數傳遞光標而不是傳遞連接有什麼問題嗎?

即:在光標

通行證從主要功能

def main(): 
    conn = pymysql.connect(...) 
    with conn as cursor: 
     func1(cursor) 
     func2(cursor) 
    conn.close() 

def func1(cursor): 
    cursor.execute('select ...') 

def func2(cursor): 
    cursor.execute('insert ...') 

通行證在連接從主要功能

def main(): 
    conn = pymysql.connect(...) 
    func1(conn) 
    func2(conn) 
    conn.close() 

def func1(conn): 
    with conn as cursor: 
     cursor.execute('select ...') 

def func2(conn): 
    with conn as cursor: 
     cursor.execute('insert ...') 
+0

我更想知道傳遞遊標是否有任何問題,這是我的首選方法,因爲它需要更少的代碼。 –

回答

3

答案來自Law of Demeter:通過光標。

這也會導致代碼略短。在這種情況下,它非常簡單,但有時可能會很多(例如,傳遞數據庫名稱與傳遞遊標)。