Guest User

Untitled

a guest
Jan 25th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import psycopg2
  2. import psycopg2.extras
  3. import csv
  4.  
  5.  
  6. def execute_query(dbname, host, user, password, query, port):
  7. try:
  8. conn = psycopg2.connect(dbname=dbname, host=host, user=user, password=password, port=port)
  9. conn.autocommit = True
  10. cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
  11. cursor.execute(query)
  12. return cursor
  13. except:
  14. print("Unable to connect to the database")
  15.  
  16.  
  17. def filter_notmatching_products(cursor):
  18. records = cursor.fetchall()
  19. print('got %s records' % len(records))
  20. not_matching = list()
  21. not_matching.append(list(records[0].keys()))
  22. for rec in records:
  23. if rec['brandid'].split('_')[0] != rec['productcode']:
  24. print('not matching brandid: %s - productcode: %s' % (rec['brandid'], rec['productcode']))
  25. not_matching.append(rec)
  26. return not_matching
  27.  
  28.  
  29. def main():
  30. print("Started")
  31.  
  32. # DB config
  33. dbname = ""
  34. host = ""
  35. user = ""
  36. password = ""
  37.  
  38. select_brands = 'select * from ancillary.master_brand'
  39. brands_cursor = execute_query(dbname, host, user, password, select_brands)
  40.  
  41. not_matching = filter_notmatching_products(brands_cursor)
  42. with open('not_matching.csv', 'w') as fp:
  43. writer = csv.writer(fp)
  44. writer.writerows(brands_cursor)
  45. writer.writerows(not_matching)
  46. print("Finished")
  47.  
  48.  
  49. if __name__ == "__main__":
  50. main()
Add Comment
Please, Sign In to add comment