2016-04-26 25 views
0

我有這個磚牆,我試圖克服。但是,我正在採用此路由(單連接共享),因爲當我必須從另一個方法訪問具有不同連接對象的特定表時,以前的方法(多連接)失敗。所以基本上,單身連接方法,請參閱下面的示例代碼;在另一個在同一類的幾種方法之間共享單個POSTGRESQL連接

import sys, psycopg2 


class myclass(): 
    def __inti__(self): 
     pass 

# Declaring DB connection 

def dbconn(self): 
    try: 
     connect_string = psycopg2.connect(host='localhost', database='', user='',password='') 
     self.con = connect_string.cursor() 
    except: 
     print('Connection Error') 

    # return dbconn 
    print(self.con, 'this is at dbconn method level') 
    return self.con 


def registration(self): 
    """ Detail of our Contacts is being collected""" 

    print('Enter 1 or 2 to update Network Provider) 
    update_data = int(input('Enter your 1 or 2 :')) 
    if update_data == 1: 
     network_name = input('Enter name of the Network Provider : ') 
     # Calling db_conn method in order to established connection to DB SERVER 
     try: 
      local_con = myclass().dbconn() 
      print(local_con, 'this is at registration method level') 

     except: 
      if local_con: 
       local_con.rollback() 

      print('Error Connection') 

     # Sending the data to the database for permanent storage 

     local_con.execute(
      "INSERT INTO network(network_name)VALUES(%s)", (network_name,)) 
     local_con.commit() 
     print('Data Save properly') 

上述代碼導致成從我的控制檯此輸出,

You can update Network Provider, API Setting and Price here 
Enter 1 or 2 to update Network Provider 
Enter your 1 or 2 :1 
Enter name of the Network Provider : starcom Nigeria 
<cursor object at 0x0000000002FD7EA0; closed: 0> this is at dbconn method level 
<cursor object at 0x0000000002FD7EA0; closed: 0> this is at registration method level 
Traceback (most recent call last): 
File "/myswitch.py", line 258, in <module> 
new_provider.registration() 
File "/myswitch.py", line 53, in registration 
local_con.commit() 
AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'commit' 

從上述輸出,我明白,我可以從dbconn訪問(self.con)()方法但是,我期望在註冊()下的本地變量的commit()屬性失敗,代碼如下 AttributeError:'psycopg2.extensions.cursor'對象沒有屬性'commit'

因此,事務未能保存到數據庫。 希望我能帶領如何解決這個問題。 在此先感謝

+0

** def __inti __ **? –

+0

請閱讀關於類和OOP。 –

回答

0

您已將「self.con = connect_string.cursor()」,因此local_con分配給遊標?提交需要來自psycopg2.connect類。

所以它需要connect_string.commit()在你的情況。

+1

謝謝,讓它工作 – Bluelily

相關問題