Python 2.7连接PostgreSQL的连接字符串(OOP方法)

6

我是Python的新手,正在尝试让它工作。我使用的是Python 2.7和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)

然而,我遇到了一个错误:“AttributeError: 'builtin_function_or_method' object has no attribute 'execute'”。我想我应该在Database类中放置类似self.execute = something的东西,但我无法弄清楚我需要放置什么。有什么建议吗?
1个回答

7
您忘了在末尾加上括号。
self.cursor = self.connection.cursor()

或者

cursor = self.cursor()

但不能两者兼得。

搞定了。谢谢兄弟! - Johann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接