The following code connects to the Postgresql. In the database there is a table 'country_details'. The first column has the names of the countries. I want the country names in a list. How do I rewrite this code in 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
CodePudding user response:
Heres an example of the same code but with a 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()
And heres how you would use it.
db = ConnectDB()
print(db. getCountries())
I recommend you watch this video Python Object Oriented Programming (OOP) - For Beginners
it helped me out. (https://youtu.be/JeznW_7DlB0)