connect.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 getItemsOfOrder(self, bookId):
  33. cursor = self.conn.cursor()
  34. cursor.execute("SELECT ori_id, ori_quantity, pro_name, ori_deliveryduedate FROM ordereditem NATURAL JOIN product WHERE ord_id = %s", (bookId,))
  35. rows = cursor.fetchall()
  36. cursor.close()
  37. return rows
  38. def commit(self):
  39. """Make the changes to the database persistent"""
  40. self.conn.commit()