Joh*_*ann 5 python postgresql psycopg2 python-2.7 postgresql-9.3
我是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)
Run Code Online (Sandbox Code Playgroud)
但是我收到错误"AttributeError:'builtin_function_or_method'对象没有属性'execute'".我想我应该在数据库类中添加类似self.execute =的东西,但我无法弄清楚究竟需要放在那里.有什么建议?
你最后错过了括号
self.cursor = self.connection.cursor()
Run Code Online (Sandbox Code Playgroud)
要么
cursor = self.cursor()
Run Code Online (Sandbox Code Playgroud)
但不是两个