如何重写此代码以从 table 中以 OOP 格式从 postgres 数据库中获取详细信息?
How do I rewrite this code to fetch the details from a table from postgres DB in OOP format?
以下代码连接到 Postgresql。在数据库中有一个table 'country_details'。第一列是国家名称。我要国家
列表中的名称。如何在 OOP 中重写此代码。
#returns the list of countries from the database
def connect_db():
con = psycopg2.connect(host='localhost',
database='Country Details',
user='postgres',
password='root')
cur = con.cursor()
cur.execute("SELECT country_name FROM country_details")
rows = cur.fetchall()
country_list = c_list(rows)
con.close()
cur.close()
return country_list
#converts the list of tuples to a list of strings
def c_list(rows):
country_list = []
for row in range(len(rows)):
country_list.append(rows[row][0])
return country_list
这是相同代码的示例,但带有 class。
class ConnectDB:
# Special method that runs when initialized
def __init__(self):
self.db = self.connect()
def connect(self):
return psycopg2.connect(host='localhost',
database='Country Details',
user='postgres',
password='root')
def _tuplesToStrings(self,rows):
return [rows[row][0] for row in range(len(rows))]
def getCountries(self):
cur = self.db.cursor()
cur.execute("SELECT country_name FROM country_details")
rows = cur.fetchall()
country_list = self._tuplesToStrings(rows)
cur.close()
return country_list
# Special method that runs when the object falls out of scope.
def __del__(self):
self.db.close()
下面是您将如何使用它。
db = ConnectDB()
print(db. getCountries())
我建议您观看此视频 Python Object Oriented Programming (OOP) - For Beginners
它帮助了我。 (https://youtu.be/JeznW_7DlB0)
以下代码连接到 Postgresql。在数据库中有一个table 'country_details'。第一列是国家名称。我要国家 列表中的名称。如何在 OOP 中重写此代码。
#returns the list of countries from the database
def connect_db():
con = psycopg2.connect(host='localhost',
database='Country Details',
user='postgres',
password='root')
cur = con.cursor()
cur.execute("SELECT country_name FROM country_details")
rows = cur.fetchall()
country_list = c_list(rows)
con.close()
cur.close()
return country_list
#converts the list of tuples to a list of strings
def c_list(rows):
country_list = []
for row in range(len(rows)):
country_list.append(rows[row][0])
return country_list
这是相同代码的示例,但带有 class。
class ConnectDB:
# Special method that runs when initialized
def __init__(self):
self.db = self.connect()
def connect(self):
return psycopg2.connect(host='localhost',
database='Country Details',
user='postgres',
password='root')
def _tuplesToStrings(self,rows):
return [rows[row][0] for row in range(len(rows))]
def getCountries(self):
cur = self.db.cursor()
cur.execute("SELECT country_name FROM country_details")
rows = cur.fetchall()
country_list = self._tuplesToStrings(rows)
cur.close()
return country_list
# Special method that runs when the object falls out of scope.
def __del__(self):
self.db.close()
下面是您将如何使用它。
db = ConnectDB()
print(db. getCountries())
我建议您观看此视频 Python Object Oriented Programming (OOP) - For Beginners
它帮助了我。 (https://youtu.be/JeznW_7DlB0)