connect.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import psycopg2
  2. class DataConsumer():
  3. """To query database"""
  4. def __init__(self, credentials):
  5. self.conn = psycopg2.connect(credentials)
  6. def __del__(self):
  7. self.conn.close()
  8. def getProductSet(self):
  9. cursor = self.conn.cursor()
  10. cursor.execute("SELECT * from Product")
  11. rows = cursor.fetchall()
  12. cursor.close()
  13. return rows
  14. def addProduct(self, name):
  15. cursor = self.conn.cursor()
  16. cursor.execute("INSERT INTO Product (pro_name) VALUES (%s)", (name,))
  17. cursor.close()
  18. def getCompanyNames(self):
  19. cursor = self.conn.cursor()
  20. cursor.execute("SELECT com_name FROM Company")
  21. ans = []
  22. for t in cursor:
  23. ans.append(t[0])
  24. cursor.close()
  25. return ans
  26. def getOrdersOfCompany(self, company):
  27. cursor = self.conn.cursor()
  28. cursor.execute("SELECT ord_id, ord_date FROM bookorder NATURAL JOIN company WHERE com_name = %s", (company,))
  29. rows = cursor.fetchall()
  30. cursor.close()
  31. return rows
  32. def commit(self):
  33. """Make the changes to the database persistent"""
  34. self.conn.commit()