gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:56:03 25 4
gpt4 key购买 nike

我是 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’对象没有属性‘execute’”。我想我应该在数据库类中放置类似 self.execute = something 的东西,但我无法弄清楚我到底需要放在那里什么。有什么建议吗?

最佳答案

最后没有括号

self.cursor = self.connection.cursor()

cursor = self.cursor()

但不是两者都是

关于Python 2.7 到 PostgreSQL 的连接字符串(OOP 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com