connect.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 getWarehousesOfCompany(self, company):
  39. cursor = self.conn.cursor()
  40. cursor.execute("SELECT war_id, add_number, add_name, add_city FROM warehouse AS w JOIN company AS c ON w.com_id = c.com_id JOIN postaladdress AS p ON w.add_id = p.add_id WHERE com_name = %s", (company,))
  41. rows = cursor.fetchall()
  42. cursor.close()
  43. return rows
  44. def commit(self):
  45. """Make the changes to the database persistent"""
  46. self.conn.commit()