Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 connection string to PostgreSQL (OOP method)

I'm new to python and I'm trying to make this work. I'm using Python 2.7 and PostgreSQL 9.3:

#! F:\Python2.7.6\python    
import psycopg2

class Database:   
    host = "192.168.56.101"
    user = "testuser"
    passwd = "passwd"
    db = "test"

    def __init__(self):
        self.connection = psycopg2.connect( host = self.host,
                                            user = self.user,
                                            password = self.passwd,
                                            dbname = self.db )
        self.cursor = self.connection.cursor

    def query(self, q):
        cursor = self.cursor
        cursor.execute(q)
        return cursor.fetchall()

    def __del__(self):
        self.connection.close()

if __name__ == "__main__":
    db = Database()
    q = "DELETE FROM testschema.test"
    db.query(q)

However I am getting an error "AttributeError: 'builtin_function_or_method' object has no attribute 'execute'". I figure I should put something like self.execute = something in the Database class, but I can't figure it out what exactly I need to put there. Any suggestions?

like image 726
Johann Avatar asked Feb 28 '14 22:02

Johann


1 Answers

You are missing the parenthesis at the end

self.cursor = self.connection.cursor()

or

cursor = self.cursor()

But not both

like image 156
Clodoaldo Neto Avatar answered Oct 12 '22 08:10

Clodoaldo Neto