我有這個磚牆,我試圖克服。但是,我正在採用此路由(單連接共享),因爲當我必須從另一個方法訪問具有不同連接對象的特定表時,以前的方法(多連接)失敗。所以基本上,單身連接方法,請參閱下面的示例代碼;在另一個在同一類的幾種方法之間共享單個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'
因此,事務未能保存到數據庫。 希望我能帶領如何解決這個問題。 在此先感謝
** def __inti __ **? –
請閱讀關於類和OOP。 –