在同一个类的几个方法之间共享单个POSTGRESQL连接

时间:2016-04-26 06:35:18

标签: python postgresql class methods singleton

我有这个砖墙,我正在努力克服。但是,我正在采用这种方式(单连接共享),因为当我不得不从另一个方法访问具有不同连接对象的特定表时,先前的方法(多连接)使我失败。所以基本上,使用单例连接方法,请参阅下面的示例代码;

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)同一个类的另一个方法registration(),但是,我期望在注册的局部变量上的commit()属性()使用以下代码失败      AttributeError:&#39; psycopg2.extensions.cursor&#39;对象没有属性&#39; commit&#39;

因此,事务无法保存到数据库。 希望我能领导如何解决这个问题。 提前致谢

1 个答案:

答案 0 :(得分:0)

您已将“self.con = connect_string.cursor()”和local_con分配给游标?提交需要来自psycopg2.connect类。

所以在你的情况下需要是connect_string.commit()。