connect.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 addOrder(self, company, houseId, proList, proQuantityList, dueDate):
  45. # Create cursor to execute SQL statements
  46. cursor = self.conn.cursor()
  47. # Create book order
  48. cursor.execute("INSERT INTO bookorder(ord_date, com_id) SELECT %s, com_id FROM company WHERE com_name = %s", (dueDate, company))
  49. # Retrieve id of the newly created bookorder
  50. cursor.execute("SELECT CURRVAL('bookorder_ord_id_seq')")
  51. ordId = cursor.fetchone()[0]
  52. # Add ordered items
  53. for k in range(len(proList)):
  54. proName = proList[k]
  55. proQuantity = proQuantityList[k]
  56. cursor.execute("INSERT INTO ordereditem(ori_quantity, ori_deliveryduedate, pro_id, ord_id, war_id) SELECT %s, %s, pro_id, %s, %s FROM product WHERE pro_name = %s", (proQuantity, dueDate, ordId, houseId, proName))
  57. cursor.close()
  58. def commit(self):
  59. """Make the changes to the database persistent"""
  60. self.conn.commit()