为什么我的 class 没有从 select 返回数据?
Why is my class not returning data from a select?
我正在学习 类,并尝试编写一个连接和 select 来自我的数据库。有没有更好的方法来做到这一点,或者我只是在某处缺少 return ? select 数据未 returning。
import psycopg2
class MyData():
def __init__(self, host="10.0.66.60", db="db", user="postgres", password="Secret"):
self.conn = psycopg2.connect(host=host, database=db, user=user, password=password)
self.cur = self.conn.cursor()
def query(self, query):
self.cur.execute(query)
def close(self):
self.cur.close()
self.conn.close()
db = MyData()
db.query("SELECT * FROM detail;")
db.close()
import psycopg2
class MyData():
def __init__(self, host="10.0.66.60", db="db", user="postgres", password="Secret"):
self.conn = psycopg2.connect(host=host, database=db, user=user, password=password)
self.cur = self.conn.cursor()
def query(self, query):
self.cur.execute(query)
# you need fetchall or fetchone to get the data, eg:
result = self.cur.fetchall()
for row in result:
print(row)
# ref: https://www.psycopg.org/docs/cursor.html#cursor.fetchall
def close(self):
self.cur.close()
self.conn.close()
db = MyData()
db.query("SELECT * FROM detail;")
db.close()
我正在学习 类,并尝试编写一个连接和 select 来自我的数据库。有没有更好的方法来做到这一点,或者我只是在某处缺少 return ? select 数据未 returning。
import psycopg2
class MyData():
def __init__(self, host="10.0.66.60", db="db", user="postgres", password="Secret"):
self.conn = psycopg2.connect(host=host, database=db, user=user, password=password)
self.cur = self.conn.cursor()
def query(self, query):
self.cur.execute(query)
def close(self):
self.cur.close()
self.conn.close()
db = MyData()
db.query("SELECT * FROM detail;")
db.close()
import psycopg2
class MyData():
def __init__(self, host="10.0.66.60", db="db", user="postgres", password="Secret"):
self.conn = psycopg2.connect(host=host, database=db, user=user, password=password)
self.cur = self.conn.cursor()
def query(self, query):
self.cur.execute(query)
# you need fetchall or fetchone to get the data, eg:
result = self.cur.fetchall()
for row in result:
print(row)
# ref: https://www.psycopg.org/docs/cursor.html#cursor.fetchall
def close(self):
self.cur.close()
self.conn.close()
db = MyData()
db.query("SELECT * FROM detail;")
db.close()