Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import psycopg2
- import psycopg2.extras
- import csv
- def execute_query(dbname, host, user, password, query, port):
- try:
- conn = psycopg2.connect(dbname=dbname, host=host, user=user, password=password, port=port)
- conn.autocommit = True
- cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
- cursor.execute(query)
- return cursor
- except:
- print("Unable to connect to the database")
- def filter_notmatching_products(cursor):
- records = cursor.fetchall()
- print('got %s records' % len(records))
- not_matching = list()
- not_matching.append(list(records[0].keys()))
- for rec in records:
- if rec['brandid'].split('_')[0] != rec['productcode']:
- print('not matching brandid: %s - productcode: %s' % (rec['brandid'], rec['productcode']))
- not_matching.append(rec)
- return not_matching
- def main():
- print("Started")
- # DB config
- dbname = ""
- host = ""
- user = ""
- password = ""
- select_brands = 'select * from ancillary.master_brand'
- brands_cursor = execute_query(dbname, host, user, password, select_brands)
- not_matching = filter_notmatching_products(brands_cursor)
- with open('not_matching.csv', 'w') as fp:
- writer = csv.writer(fp)
- writer.writerows(brands_cursor)
- writer.writerows(not_matching)
- print("Finished")
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment